一 需求
求算学生学科成绩之和,分数之和,学费之和。
学号 | 成绩 | 学分 | 学费 |
123 | 78 | 99 | 340 |
123 | 45 | 76 | 367 |
321 | 65 | 54 | 387 |
二 分析
这里是对学号单字段分组,分别对成绩、分数、学费三个字段求和。
三 代码
package com.cakin.javademo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ClassName: GroupManyColSum https://www.cnblogs.com/stjwy/p/14074175.html
* @Description: 单字段分组,多字段求和
* @Date: 2021/3/13
* @Author: cakin
*/
public class GroupManyColSum {
/**
* @className: GroupManyColSum
* @description: 单字段分组,多字段求和
* @date: 2021/3/14
* @author: cakin
*/
public static void main(String[] args) {
List<Student> studentList = new ArrayList();
studentList.add(new Student("123", 78L, 99, new BigDecimal(340)));
studentList.add(new Student("123", 45L, 76, new BigDecimal(367)));
studentList.add(new Student("321", 65L, 54, new BigDecimal(387)));
// 以 code 为分组字段,对 achievement score money 分别求和
List<Student> list = studentList
.stream()
// groupingBy的第1个参数为分组字段,第2个参数为求和公式
.collect(Collectors.groupingBy(Student::getCode, Collectors.reducing((sum, s) ->
new Student(s.getCode(), sum.getAchievement() + s.getAchievement(), sum.getScore() + s.getScore(), sum.getMoney().add(s.getMoney())))))
.entrySet()
.stream()
.map(c -> c.getValue().get())
.collect(Collectors.toList());
for (Student student : list) {
System.out.println(student);
}
}
}
/**
* @className: GroupManyColSum
* @description: 学生类
* @date: 2021/3/14
* @author: cakin
*/
class Student {
/**
* 学号
*/
private String code;
/**
* 成绩
*/
private Long achievement;
/**
* 学分
*/
private Integer score;
/**
* 学费
*/
private BigDecimal money;
public Student() {
}
public Student(String code, Long achievement, Integer score, BigDecimal money) {
this.code = code;
this.achievement = achievement;
this.score = score;
this.money = money;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getAchievement() {
return achievement;
}
public void setAchievement(Long achievement) {
this.achievement = achievement;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
@Override
public String toString() {
return "Student{" +
"code='" + code + '\'' +
", achievement=" + achievement +
", score=" + score +
", money=" + money +
'}';
}
}
四 测试
Student{code='321', achievement=65, score=54, money=387}
Student{code='123', achievement=123, score=175, money=707}