使用Collectors.toSet()可将流中元素收集为Set实现去重,依赖对象的equals和hashCode方法判断重复,对自定义对象需正确重写这两个方法;若需保持插入顺序,可用Collectors.toCollection(LinkedHashSet::new)替代。

在Java 8及以上版本中,Collectors.toSet() 是处理流(Stream)时常用的收集器之一,用于将流中的元素收集到一个 Set 集合中。由于 Set 接口的特性是不允许重复元素,因此使用 Collectors.toSet() 可以实现自动去重。
基本用法:使用 Collectors.toSet() 去重
当你有一个包含重复元素的数据源(如 List),可以通过 Stream 流式处理并使用 Collectors.toSet() 收集为无重复元素的集合。
Listlist = Arrays.asList("apple", "banana", "apple", "orange", "banana"); Set uniqueSet = list.stream() .collect(Collectors.toSet()); System.out.println(uniqueSet); // 输出可能为:[apple, banana, orange]
这个例子中,原始列表含有重复字符串,通过流处理后使用 toSet() 自动去除重复项,最终得到唯一元素的 Set。
注意点:元素的 equals 和 hashCode 方法
Set 判断是否重复依赖于对象的 equals() 和 hashCode() 方法。对于自定义对象,必须正确重写这两个方法,否则可能导致去重失败。
立即学习“Java免费学习笔记(深入)”;
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);
}
}
然后使用:
Listpeople = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Alice", 25) ); Set uniquePeople = people.stream() .collect(Collectors.toSet()); System.out.println(uniquePeople.size()); // 输出 2,成功去重
替代方案:保持顺序的去重(LinkedHashSet)
Collectors.toSet() 返回的是一个 HashSet 类型的实例,不保证元素顺序。如果希望保留插入顺序,可以使用 Collectors.toCollection(LinkedHashSet::new)。
SetorderedSet = list.stream() .collect(Collectors.toCollection(LinkedHashSet::new));
这样收集的结果是一个 LinkedHashSet,既能去重,又能保持元素首次出现的顺序。
基本上就这些。使用Collectors.toSet() 实现流去重简单高效,关键是确保对象的 equals 和 hashCode 正确实现。根据需求选择合适的 Set 实现类型即可。










