答案:Java中Stream.distinct()基于equals()去重,保留首个元素;基本类型直接使用,自定义对象需重写equals和hashCode;按字段去重可用Set配合filter实现。

Java 中的 Stream.distinct() 方法用于去除流中重复的元素,它基于元素的 equals() 方法来判断两个元素是否相等。调用 distinct() 后,流中每个“相同”的元素只会保留第一个出现的实例,后续重复项会被过滤掉。
对于基本数据类型包装类(如 Integer、String)等,distinct() 可直接使用,因为这些类已经正确实现了 equals 和 hashCode 方法。
List<String> names = Arrays.asList("Alice", "Bob", "Alice", "Charlie", "Bob");
List<String> uniqueNames = names.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueNames); // 输出: [Alice, Bob, Charlie]
如果要对自定义对象去重,必须确保类正确重写了 equals() 和 hashCode() 方法,否则 distinct() 会基于引用比较,无法识别逻辑上的重复。
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
// getter 和 toString 方法略
}
使用示例:
立即学习“Java免费学习笔记(深入)”;
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Alice", 25)
);
List<Person> uniquePeople = people.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniquePeople.size()); // 输出: 2
若想根据对象的某个字段去重(例如只看 name 去重),可借助一个辅助的 Set 来跟踪已出现的值。
Set<String> seen = new HashSet<>();
List<Person> uniqueByName = people.stream()
.filter(person -> seen.add(person.getName())) // add 返回 false 表示已存在
.collect(Collectors.toList());
这段代码保留第一次出现的同名 person,实现按 name 字段去重。
基本上就这些。只要记住:distinct() 依赖 equals 和 hashCode,基础类型开箱即用,对象需手动重写,按字段去重则配合 Set 使用 filter 更灵活。不复杂但容易忽略细节。
以上就是Java Stream.distinct方法如何去重的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号