Collectors.toSet() 返回无序、不可变、不支持null的HashSet;需有序用LinkedHashSet::new,需排序用TreeSet::new,含null需先filter。

Java 中用 Stream.collect(Collectors.toSet()) 可以把流中的元素收集为一个 Set,但要注意它返回的是不保证顺序、不可变(实际是 HashSet 实例)、且不支持 null 元素的集合。
Collectors.toSet() 的基本用法
它是最简单的无参收集器之一,适用于去重并忽略顺序的场景:
- 自动去除重复元素(基于
equals()和hashCode()) - 底层使用
HashSet,所以插入顺序不保留 - 如果流中含
null,运行时抛NullPointerException
示例:
List<String> list = Arrays.asList("a", "b", "a", "c");
Set<String> set = list.stream().collect(Collectors.toSet()); // 可能是 [a, b, c] 或 [b, a, c] 等
想保持插入顺序?用 toCollection(LinkedHashSet::new)
Collectors.toSet() 不保证顺序,若需按首次出现顺序去重,应显式指定集合类型:
立即学习“Java免费学习笔记(深入)”;
- 用
Collectors.toCollection(LinkedHashSet::new)替代 -
LinkedHashSet既去重又维护插入顺序
示例:
Set<String> orderedSet = list.stream()
.collect(Collectors.toCollection(LinkedHashSet::new)); // 总是 [a, b, c]
需要线程安全或特定实现?手动指定构造器
默认的 toSet() 返回普通 HashSet,无法控制容量、加载因子或并发性。如需定制:
- 并发场景可用
Collectors.toCollection(ConcurrentHashMap.newKeySet()::add)(JDK 12+) - 或直接用
toCollection(TreeSet::new)获得有序(自然序或自定义序)的去重结果 - 注意:TreeSet 要求元素可比较,否则运行时报
ClassCastException
示例(升序):
Set<Integer> sortedSet = Arrays.asList(3, 1, 4, 1, 5)
.stream()
.collect(Collectors.toCollection(TreeSet::new)); // [1, 3, 4, 5]
注意 null 元素和空流处理
toSet() 对 null 零容忍,但空流是安全的:
- 空流调用
collect(toSet())返回空HashSet,不会出错 - 含
null会立即抛NullPointerException(在收集过程中) - 如需容忍
null,先过滤:stream.filter(Objects::nonNull).collect(toSet())


















