Collectors.toList() 是 Java 8 Stream API 中用于将流元素收集到 List 的常用收集器,返回的列表基于 ArrayList 实现、允许重复且不保证线程安全;基本语法为 stream.collect(Collectors.toList()),常用于数据过滤、转换后收集,如字符串转大写或提取对象属性;注意事项包括:生成的列表不可直接修改结构、若需不可变列表应使用 Collectors.toUnmodifiableList()(Java 10+),指定实现类型可用 Collectors.toCollection(LinkedList::new);典型应用场景有筛选符合条件的数据、转换后汇总及与 groupingBy 等组合实现分组收集。

在Java 8引入的Stream API中,Collectors.toList() 是最常用的收集器之一,用于将流(Stream)中的元素收集到一个List集合中。它属于 java.util.stream.Collectors 类提供的静态方法,常配合 collect() 方法使用。
该方法返回一个 Collector,可以将流中的元素累积到一个新的 ArrayList 实例中。生成的 List 是可变的、无序的,并且允许重复元素。它不保证线程安全,也不保证返回列表的类型一定是 ArrayList,具体实现由JDK内部决定。
基本语法如下:
stream.collect(Collectors.toList())
立即学习“Java免费学习笔记(深入)”;
以下是一个简单的例子,展示如何将一个字符串列表转换为大写并收集为新的列表:
List<String> words = Arrays.asList("hello", "world", "java", "stream");
List<String> upperCaseWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperCaseWords);
// 输出:[HELLO, WORLD, JAVA, STREAM]
再比如,从对象流中提取属性:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter 方法
public String getName() { return name; }
}
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30)
);
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(names);
// 输出:[Alice, Bob]
虽然 Collectors.toList() 使用方便,但在某些场景下需要注意以下几点:
List<String> linkedResult = stream
.collect(Collectors.toCollection(LinkedList::new));
Collectors.toList() 常用于以下场景:
例如按条件分组:
Map<Integer, List<Person>> groupedByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 每个value都是通过 toList() 隐式收集的
以上就是在Java中如何使用Collectors.toList收集流结果_流收集方法与应用说明的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号