Java中将流转为List最常用Collectors.toList(),返回等效ArrayList;需特定实现可用toCollection指定构造器;去重用distinct(),过滤用filter()。

Java 中用 collect 将流转为 List,最常用的是 Collectors.toList()。
使用 Collectors.toList() 收集为 ArrayList
这是最直接的方式,适用于大多数场景。返回的 List 是 ArrayList 的实例(具体实现类由 JDK 决定,但行为等同于 ArrayList)。
示例:
List<String> list = Stream.of("a", "b", "c")
.collect(Collectors.toList());
指定具体 List 实现类型(如 LinkedList)
如果需要特定实现(比如要求频繁插入/删除),可配合 Collectors.toCollection() 指定构造器:
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
立即学习“Java免费学习笔记(深入)”;
Collectors.toCollection(LinkedList::new)Collectors.toCollection(ArrayList::new)Collectors.toCollection(() -> new CopyOnWriteArrayList<>())
示例:
List<String> linkedList = Stream.of("x", "y", "z")
.collect(Collectors.toCollection(LinkedList::new));
去重后收集为 List
若需去重,可在流中先调用 distinct(),再收集:
List<Integer> uniqueList = Stream.of(1, 2, 2, 3, 1)
.distinct()
.collect(Collectors.toList()); // [1, 2, 3]
按条件过滤后再收集
结合 filter() 可灵活控制入列元素:
List<String> filtered = Stream.of("apple", "banana", "cherry")
.filter(s -> s.length() > 5)
.collect(Collectors.toList()); // ["banana", "cherry"]

















