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](顺序不定),且自动去重
</string></string>
注意:返回的 Set 可能不可修改
Java 9+ 中 Collectors.toSet() 默认返回的是 Set 接口的一个轻量实现(如 UnmodifiableSet 包装类),**调用 add()、remove() 会抛 UnsupportedOperationException**。如果后续要修改,得显式转成可变集合:
- 用
new HashSet(...)包一层:SetmutableSet = new HashSet(list.stream().collect(Collectors.toSet())); - 或直接用
Collectors.toCollection(HashSet::new):Setset = list.stream().collect(Collectors.toCollection(HashSet::new));
想控制 Set 类型?用 toCollection
如果你明确需要 LinkedHashSet(保持插入顺序)或 TreeSet(自然排序/自定义排序),不能用 toSet(),得用 toCollection:
-
LinkedHashSet(有序):Setordered = list.stream().collect(Collectors.toCollection(LinkedHashSet::new)); -
TreeSet(排序):Setsorted = numbers.stream().collect(Collectors.toCollection(TreeSet::new));
或带比较器:TreeSet::new+Comparator.reverseOrder()
数组转 Set 的写法
数组没有 stream() 方法,得先转成流:
- 对象数组(如
String[]):String[] arr = {"x", "y", "x"};<br>Set<string> set = Arrays.stream(arr).collect(Collectors.toSet());</string> - 基本类型数组(如
int[])需用Arrays.stream()的特化方法:int[] nums = {1, 2, 1};<br>Set<integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet());</integer>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











