distinct()可对集合去重,简单类型直接使用,自定义对象需重写equals和hashCode,按字段去重可用toMap收集器实现。

Java 中的 Stream.distinct() 方法可以很方便地对集合中的元素进行去重操作。它会返回一个由原流中不重复元素组成的新的流,从而避免修改原始数据。
对于基本类型的包装类(如 String、Integer),distinct() 可以直接使用,因为这些类已经重写了 equals() 和 hashCode() 方法。
示例:去除字符串列表中的重复项
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana");
List<String> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctList); // 输出: [apple, banana, orange]
如果要对自定义对象去重,必须确保该类正确实现了 equals() 和 hashCode() 方法,否则 distinct() 无法识别两个对象是否相等。
立即学习“Java免费学习笔记(深入)”;
例如,有一个 Person 类:
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 方法省略
}
使用 distinct() 去除重复的 Person 对象:
List<Person> people = Arrays.asList(
new Person("张三", 25),
new Person("李四", 30),
new Person("张三", 25)
);
List<Person> distinctPeople = people.stream()
.distinct()
.collect(Collectors.toList());
distinctPeople.forEach(System.out::println); // 只输出两个对象,重复的被去除
有时我们只想根据某个字段(如 id 或 name)去重,而不是整个对象完全一致。这时不能直接用 distinct(),但可以通过 Collectors.toMap() 或中间映射实现。
方法一:使用 toMap 保留唯一 key 的对象
List<Person> uniqueByName = people.stream()
.collect(Collectors.toMap(
Person::getName, // 以 name 为 key
p -> p, // value 是对象本身
(existing, replacement) -> existing // 如果重复,保留第一个
))
.values()
.stream()
.collect(Collectors.toList());
这样就实现了按姓名去重,只保留每个名字的第一个 Person 对象。
基本上就这些。只要记住:简单类型直接用,对象记得重写 equals 和 hashCode,特殊去重要借助 map 收集策略。使用 distinct() 配合 Stream API,代码简洁又高效。
以上就是如何使用Java的Stream.distinct去重集合元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号