stream().collect(Collectors.toSet())可将List或数组转为去重Set,但返回的是无序、可能不可变的Set;需可变时用toCollection(HashSet::new),需有序用LinkedHashSet::new,需排序用TreeSet::new。

直接用 stream().collect(Collectors.toSet()) 就能把集合或数组转成 Set,但要注意它返回的是一个**无序、不可变性不确定、底层实现不固定的 HashSet(通常是)**,不是你手动 new 的那个可变 HashSet。
基础用法:List → Set
最常见场景是从 List 转 Set 去重:
List<String> list = Arrays.asList("a", "b", "a", "c");
Set<String> set = list.stream().collect(Collectors.toSet());
// 结果可能是 [a, b, c](顺序不定),且自动去重
注意:返回的 Set 可能不可修改
Java 9+ 中 Collectors.toSet() 默认返回的是 Set 接口的一个轻量实现(如 UnmodifiableSet 包装类),**调用 add()、remove() 会抛 UnsupportedOperationException**。如果后续要修改,得显式转成可变集合:
- 用
new HashSet(...)包一层:Set<string> mutableSet = new HashSet(list.stream().collect(Collectors.toSet()));</string> - 或直接用
Collectors.toCollection(HashSet::new):Set<string> set = list.stream().collect(Collectors.toCollection(HashSet::new));</string>
想控制 Set 类型?用 toCollection
如果你明确需要 LinkedHashSet(保持插入顺序)或 TreeSet(自然排序/自定义排序),不能用 toSet(),得用 toCollection:
立即学习“Java免费学习笔记(深入)”;
-
LinkedHashSet(有序):Set<string> ordered = list.stream().collect(Collectors.toCollection(LinkedHashSet::new));</string> -
TreeSet(排序):Set<integer> sorted = numbers.stream().collect(Collectors.toCollection(TreeSet::new));</integer>
或带比较器:TreeSet::new+Comparator.reverseOrder()
数组转 Set 的写法
数组没有 stream() 方法,得先转成流:
- 对象数组(如
String[]):String[] arr = {"x", "y", "x"};<br>Set<String> set = Arrays.stream(arr).collect(Collectors.toSet()); - 基本类型数组(如
int[])需用Arrays.stream()的特化方法:int[] nums = {1, 2, 1};<br>Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet());


















