美文网首页
lambda列求和

lambda列求和

作者: 霹雳解锋镝 | 来源:发表于2020-01-20 17:56 被阅读0次
    学习成绩汇总
    创建对象
    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) {
            ## 准备数据
            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中间结果(会使用第一个元素的地址)、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对象中的值 不推荐
            //方式二  初始化一个对象,中间结果使用此地址
            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;
            });
        }
    }

    相关文章

      网友评论

          本文标题:lambda列求和

          本文链接:https://www.haomeiwen.com/subject/elajzctx.html