使用Stream API的Collectors.groupingBy可实现集合分组统计,如按部门统计员工数量:Map<String, Long> deptCount = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));2. 可结合Collectors.summingInt等进行数值求和,如计算各部门工资总额;3. 支持平均值、最值及多指标统计,如averagingDouble和summarizingInt;4. 支持多级分组,如先按部门再按职位统计,生成嵌套Map;需注意空值处理及key字段的equals和hashCode实现。

在Java中,可以使用Stream API结合Collectors.groupingBy对集合进行分组统计。这种方式简洁高效,适用于各种分组聚合场景,比如按属性分组并计算数量、求和、平均值等。
使用Collectors.groupingBy配合Collectors.counting()可实现按某个字段分组并统计每组元素个数。
假设有一个员工类:
<font face="Courier New,Courier,monospace">class Employee {
private String department;
private String name;
// 构造方法、getter省略
}</font>统计每个部门的员工人数:
立即学习“Java免费学习笔记(深入)”;
<font face="Courier New,Courier,monospace">Map<String, Long> deptCount = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));</font>结果是一个Map,键为部门名,值为该部门人数。
如果需要对分组内的数值字段求和,比如统计每个部门的工资总额,可使用Collectors.summingInt/Long/Double。
<font face="Courier New,Courier,monospace">Map<String, Integer> salarySum = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)
));</font>除了计数和求和,还可以计算平均值、最大值、最小值或同时获取多个统计信息。
计算平均工资:<font face="Courier New,Courier,monospace">Map<String, Double> avgSalary = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
));</font><font face="Courier New,Courier,monospace">Map<String, IntSummaryStatistics> stats = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.summarizingInt(Employee::getSalary)
));</font>每个value包含count、sum、min、max、average等信息。
支持多层分组,例如先按部门再按职位统计人数。
<font face="Courier New,Courier,monospace">Map<String, Map<String, Long>> twoLevelGroup = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.groupingBy(Employee::getPosition, Collectors.counting())
));</font>返回的是一个嵌套Map,外层Key是部门,内层Key是职位,值为对应人数。
基本上就这些常用方式。通过组合groupingBy与不同的下游收集器,能灵活实现各类分组统计需求。实际使用时注意空值处理,并确保分组字段适合作为Map的key(即正确重写equals和hashCode)。
以上就是在Java中如何利用Collectors对集合分组统计的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号