java分组求语文得分和数学得分
时间: 2024-02-05 14:13:10 浏览: 29
假设有一个学生类Student,其中包含姓名、语文成绩和数学成绩三个属性,可以使用Java中的Stream API对学生集合进行分组和计算语文和数学成绩的总和。
示例代码如下:
```java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("小明", 80, 90),
new Student("小红", 90, 85),
new Student("小刚", 85, 95),
new Student("小李", 75, 80),
new Student("小张", 95, 90)
);
Map<String, List<Student>> groupBy = students.stream().collect(Collectors.groupingBy(Student::getName));
groupBy.forEach((name, list) -> {
int chineseScore = list.stream().mapToInt(Student::getChineseScore).sum();
int mathScore = list.stream().mapToInt(Student::getMathScore).sum();
System.out.println(name + ":语文总分为" + chineseScore + ",数学总分为" + mathScore);
});
}
static class Student {
private String name;
private int chineseScore;
private int mathScore;
public Student(String name, int chineseScore, int mathScore) {
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
}
}
```
输出结果为:
```
小张:语文总分为95,数学总分为90
小明:语文总分为80,数学总分为90
小李:语文总分为75,数学总分为80
小红:语文总分为90,数学总分为85
小刚:语文总分为85,数学总分为95
```