最常用方式是collect(collectors.tolist())或collect(collectors.toset()):tolist()保持顺序但jdk16+返回不可变列表,需可变时用tocollection(arraylist::new);toset()去重无序,需有序用linkedhashset,需排序用treeset。

直接用 collect(Collectors.toList()) 或 collect(Collectors.toSet()) 即可,这是最常用、最简洁的方式。
收集为 List:保持顺序且允许重复
toList() 会按流中元素的原始顺序收集,生成一个 ArrayList(JDK 16+ 返回的是不可变列表,如需可变列表建议显式指定)。
示例:
List<string> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());</string>
注意:如果后续要修改该列表,JDK 16 及以后版本返回的是不可变集合,可改用:
-
collect(Collectors.toCollection(ArrayList::new))—— 明确创建可变ArrayList - 或先收集再复制:
new ArrayList(stream.collect(Collectors.toList()))
收集为 Set:自动去重,不保证顺序
toSet() 默认使用 HashSet,元素无序且唯一。它不保证插入顺序或遍历顺序。
示例:
Set<string> uniqueNames = people.stream()
.map(Person::getName)
.collect(Collectors.toSet());</string>
若需有序的 Set(如按插入顺序),可用:
collect(Collectors.toCollection(LinkedHashSet::new))
若需自然排序(如字符串字典序),可用:
collect(Collectors.toCollection(TreeSet::new))
自定义收集器:更灵活的控制
当默认方法不满足需求时(比如要指定容量、线程安全、或特殊类型),可手写收集器:
- 构建带初始容量的
ArrayList:collect(Collector.of(ArrayList::new, ArrayList::add, (a, b) -> { a.addAll(b); return a; })) - 并发环境下用
ConcurrentHashMap.newKeySet()替代toSet(): collect(Collectors.toCollection(ConcurrentHashMap::newKeySet))
常见陷阱提醒
别在并行流中依赖 toList() 的顺序——虽然通常能保持,但 toSet() 在并行下更不可控;null 元素可被加入 List,但多数 Set 实现(如 HashSet)允许一个 null,而 TreeSet 直接抛 NullPointerException。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











