You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Stream将School对象的Country映射为学生总数?

按国家分组并累加学生总数的Java Stream实现

要实现将Stream<School>按国家分组,同时累加每个国家的学生总数,核心是利用Stream的collect方法结合分组收集器与求和收集器完成操作。

核心代码实现

import java.util.Map;
import java.util.stream.Collectors;

// 参考School类定义
class School {
    private String country;
    private int numStudents;

    public String getCountry() { return country; }
    public int getNumStudents() { return numStudents; }

    // 构造方法等其他必要实现
}

// 处理Stream生成目标映射
Map<String, Integer> countryToTotalStudents = allSchools.stream()
    .collect(Collectors.groupingBy(
        School::getCountry,  // 以国家名称作为分组键
        Collectors.summingInt(School::getNumStudents)  // 对每组的学生数求和
    ));

关键逻辑说明

  • Collectors.groupingBy(School::getCountry):将所有School对象按getCountry()返回的国家名称分组,默认会把同国家的School对象归为一个列表。
  • 第二个参数Collectors.summingInt(School::getNumStudents)是下游收集器,它会遍历每组的School对象,提取每个对象的学生数并累加,最终将分组后的列表替换为累加得到的总学生数。

扩展:处理大数学生数

如果学生总数可能超出int范围,改用summingLong即可适配:

Map<String, Long> countryToTotalStudents = allSchools.stream()
    .collect(Collectors.groupingBy(
        School::getCountry,
        Collectors.summingLong(School::getNumStudents)
    ));

和频率统计的区别

你之前用的重复元素频率统计(如Collectors.counting())是统计每组元素的个数;而这里需要对元素的数值属性进行求和,因此必须使用summingInt/summingLong这类专门的数值累加收集器。

内容的提问来源于stack exchange,提问作者Kevin Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 02:18:18