學(xué)習(xí)成績匯總
創(chuàng)建對象
public class Student {
public Student(Integer chinese, Integer math, Integer english, Integer physics) {
Chinese = chinese;
this.math = math;
English = english;
this.physics = physics;
}
private Integer Chinese;
private Integer math;
private Integer English;
private Integer physics;
}
測試
public class Test {
public static void main(String[] args) {
## 準(zhǔn)備數(shù)據(jù)
Student student1 = new Student(100, 90, 80, 89);
Student student2 = new Student(83, 80, 75, 73);
Student student3 = new Student(90, 100, 80, 80);
Student student4 = new Student(60, 98, 98, 79);
List<Student> list = new ArrayList();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
// reduce使用 acc中間結(jié)果(會使用第一個元素的地址)笼裳、bb是Stream的元素
// 方式一
Student student5 = list.stream().reduce((acc, bb) -> {
acc.setChinese(acc.getChinese() + bb.getChinese());
acc.setEnglish(acc.getEnglish() + bb.getEnglish());
acc.setMath(acc.getMath() + bb.getEnglish());
acc.setPhysics(acc.getPhysics() + bb.getPhysics());
return acc;
}).get();
list.add(student5);
System.out.println(list);
// 此上方式會修改student1對象中的值 不推薦
//方式二 初始化一個對象纹蝴,中間結(jié)果使用此地址
Student stu0 = new Student(0, 0, 0, 0);
Student reduce = list.stream().reduce(stu0, (stu1, stu2) -> {
stu1.setChinese(stu1.getChinese() + stu2.getChinese());
stu1.setEnglish(stu1.getEnglish() + stu2.getEnglish());
stu1.setMath(stu1.getMath() + stu2.getMath());
stu1.setPhysics(stu1.getPhysics() + stu2.getPhysics());
return stu1;
});
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者