lambda列求和

學習成績匯總
創(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) {
        ## 準備數(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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容