Collectors是Java中用于将流元素收集到集合或进行聚合操作的工具类,提供toList、toSet、toMap实现数据收集与转换,支持分组groupingBy、分区partitioningBy、统计counting、求和summingInt及字符串连接joining等功能,极大简化数据处理。

在Java中,Collectors 是 java.util.stream.Collectors 类提供的工具集合,用于将流(Stream)中的元素收集到目标容器中,比如 List、Set、Map,或者进行分组、分区、拼接等操作。它是函数式编程中非常实用的组件。
最常见的用途是把流中的元素收集到集合类型中:
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
Set<String> uniqueNames = people.stream()
.map(Person::getName)
.collect(Collectors.toSet());
// 收集到 LinkedList
LinkedList<String> linkedList = stream.collect(
Collectors.toCollection(LinkedList::new)
);
使用 Collectors.toMap() 可以将流中的元素转为 Map,需提供键和值的映射函数。
Map<Integer, String> idToName = people.stream()
.collect(Collectors.toMap(
Person::getId,
Person::getName
));
如果存在重复 key,会抛出异常。此时可传入第四个参数(合并函数)解决冲突:
立即学习“Java免费学习笔记(深入)”;
Map<Integer, String> idToName = people.stream()
.collect(Collectors.toMap(
Person::getId,
Person::getName,
(existing, replacement) -> existing // 保留第一个
));
Collectors.groupingBy() 按条件分组,返回一个 Map,key 是分组依据。
// 按年龄分组
Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 多级分组:先按年龄,再按性别
Map<Integer, Map<String, List<Person>>> groupByAgeAndGender = people.stream()
.collect(Collectors.groupingBy(
Person::getAge,
Collectors.groupingBy(Person::getGender)
));
Collectors.partitioningBy() 是特殊的分组,只分为两组:true 和 false。
// 按是否成年分区
Map<Boolean, List<Person>> adultPartition = people.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() >= 18));
Collectors 提供了多种聚合操作:
Long count = people.stream()
.collect(Collectors.counting());
IntSummaryStatistics stats = people.stream()
.collect(Collectors.summarizingInt(Person::getAge));
int maxAge = people.stream()
.collect(Collectors.maxBy(Comparator.comparing(Person::getAge)))
.map(Person::getAge)
.orElse(0);
使用 Collectors.joining() 将字符串拼接起来,支持分隔符、前缀和后缀。
String names = people.stream()
.map(Person::getName)
.collect(Collectors.joining(", ", "Names: ", "."));
// 输出示例:Names: Alice, Bob, Charlie.
以上就是在Java中如何使用Collectors收集流结果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号