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

如何用Java 8 Stream API实现同名学生分数合并(键值对形式)

用Java 8 Stream API实现同名学生成绩求和

现有一个存储Student对象的ArrayList,Student类包含studentname(学生姓名)、rollno(学号)、studentmarks(成绩)三个属性。需要实现的逻辑是:将所有同名学生的成绩相加,最终输出以学生姓名-总分为键值对的结果。

Student类核心定义

public class Student {
    private String studentname;
    private int rollno;
    private int studentmarks;

    // 构造方法
    public Student(int rollno, String studentname, int studentmarks) {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentmarks = studentmarks;
    }

    // 必要的getter方法
    public String getStudentname() {
        return studentname;
    }

    public int getStudentmarks() {
        return studentmarks;
    }
}

示例列表初始化代码

List<Student> arraylist = new ArrayList<>();
arraylist.add(new Student(223, "Chaitanya", 26));
arraylist.add(new Student(245, "Rahul", 24));
arraylist.add(new Student(246, "Rahul", 25));

方式一:使用Collectors.groupingBy + Collectors.summingInt

这是最直观的实现方式,通过groupingBy按学生姓名分组,再用summingInt对每组成绩求和:

Map<String, Integer> nameToTotalMarks = arraylist.stream()
    .collect(Collectors.groupingBy(
        Student::getStudentname,  // 分组依据:学生姓名
        Collectors.summingInt(Student::getStudentmarks)  // 分组内操作:累加成绩
    ));

// 输出结果
nameToTotalMarks.forEach((name, total) -> System.out.println(name + " - " + total));

输出结果:

Chaitanya - 26
Rahul - 49

方式二:使用Collectors.toMap

如果需要自定义重复键的处理逻辑,可使用toMap,指定遇到同名学生时累加成绩:

Map<String, Integer> nameToTotalMarks = arraylist.stream()
    .collect(Collectors.toMap(
        Student::getStudentname,
        Student::getStudentmarks,
        (existingMarks, newMarks) -> existingMarks + newMarks  // 重复键时的合并规则
    ));

// 输出结果
nameToTotalMarks.forEach((name, total) -> System.out.println(name + " - " + total));

此方式输出结果与方式一完全一致,适合需要灵活调整合并逻辑的场景。


内容的提问来源于stack exchange,提问作者Umesh Sulakude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:31:16