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

在Java中,Collectors 是 java.util.stream.Collectors 类提供的工具集合,用于将流(Stream)中的元素收集到目标容器中,比如 List、Set、Map,或者进行分组、分区、拼接等操作。它是函数式编程中非常实用的组件。
收集到集合中
最常见的用途是把流中的元素收集到集合类型中:
- Collectors.toList():收集为 ArrayList
- Collectors.toSet():收集为 HashSet,自动去重
- Collectors.toCollection(集合构造器):指定具体集合类型
Listnames = people.stream() .map(Person::getName) .collect(Collectors.toList()); Set uniqueNames = people.stream() .map(Person::getName) .collect(Collectors.toSet()); // 收集到 LinkedList LinkedList linkedList = stream.collect( Collectors.toCollection(LinkedList::new) );
转换为 Map
使用 Collectors.toMap() 可以将流中的元素转为 Map,需提供键和值的映射函数。
MapidToName = people.stream() .collect(Collectors.toMap( Person::getId, Person::getName ));
如果存在重复 key,会抛出异常。此时可传入第四个参数(合并函数)解决冲突:
立即学习“Java免费学习笔记(深入)”;
篇文章是针对git版本控制和工作流的总结,如果有些朋友之前还没使用过git,对git的基本概念和命令不是很熟悉,可以从以下基本教程入手: Git是分布式版本控制系统,与SVN类似的集中化版本控制系统相比,集中化版本控制系统虽然能够令多个团队成员一起协作开发,但有时如果中央服务器宕机的话,谁也无法在宕机期间提交更新和协同开发。甚至有时,中央服务器磁盘故障,恰巧又没有做备份或备份没及时,那就可能有丢失数据的风险。感兴趣的朋友可以过来看看
MapidToName = people.stream() .collect(Collectors.toMap( Person::getId, Person::getName, (existing, replacement) -> existing // 保留第一个 ));
分组与分区
Collectors.groupingBy() 按条件分组,返回一个 Map,key 是分组依据。
// 按年龄分组 Map> byAge = people.stream() .collect(Collectors.groupingBy(Person::getAge)); // 多级分组:先按年龄,再按性别 Map >> groupByAgeAndGender = people.stream() .collect(Collectors.groupingBy( Person::getAge, Collectors.groupingBy(Person::getGender) ));
Collectors.partitioningBy() 是特殊的分组,只分为两组:true 和 false。
// 按是否成年分区 Map> adultPartition = people.stream() .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));
聚合与统计
Collectors 提供了多种聚合操作:
- Collectors.counting():计数
- Collectors.summingInt():对 int 值求和
- Collectors.averagingDouble():求平均值
- Collectors.maxBy()/minBy():获取最大/最小值
- Collectors.summarizingInt():生成统计信息(总数、总和、平均、最大、最小)
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.
基本上就这些常用方式。根据实际需求组合使用,能极大简化数据处理逻辑。









