登录
首页 >  文章 >  java教程

Java集合分组统计方法详解

时间:2025-12-16 17:13:31 314浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《Java集合分组统计技巧》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

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

在Java中如何利用Collectors对集合分组统计

在Java中,可以使用Stream API结合Collectors.groupingBy对集合进行分组统计。这种方式简洁高效,适用于各种分组聚合场景,比如按属性分组并计算数量、求和、平均值等。

1. 按字段分组并统计数量

使用Collectors.groupingBy配合Collectors.counting()可实现按某个字段分组并统计每组元素个数。

示例:

假设有一个员工类:

<font face="Courier New,Courier,monospace">class Employee {
    private String department;
    private String name;

    // 构造方法、getter省略
}</font>

统计每个部门的员工人数:

<font face="Courier New,Courier,monospace">Map<String, Long> deptCount = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));</font>

结果是一个Map,键为部门名,值为该部门人数。

2. 分组后进行数值求和

如果需要对分组内的数值字段求和,比如统计每个部门的工资总额,可使用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>

3. 分组后计算平均值或其它聚合操作

除了计数和求和,还可以计算平均值、最大值、最小值或同时获取多个统计信息。

计算平均工资:
<font face="Courier New,Courier,monospace">Map<String, Double> avgSalary = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.averagingDouble(Employee::getSalary)
    ));</font>
获取完整统计信息(如IntSummaryStatistics):
<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等信息。

4. 多级分组

支持多层分组,例如先按部门再按职位统计人数。

<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集合分组统计方法详解》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>