Java lambda 分組后多列求和


主要思路是reducing,可以像sql一樣分組后多列求和處理成新對象等;

 

select code,max(name)as name,sum(chengJi)as chengJi,sum(age)as age,sum(value)as value from student group by code 

將上邊sql翻譯成java 后為如下代碼

@Data
    public class Student{
        public Student() {
        }

        public Student(String code, String name, Long chengJi, Integer age, BigDecimal value) {
            this.code = code;
            this.name = name;
            this.chengJi = chengJi;
            this.age = age;
            this.value = value;
        }

        private String code;
        private String name;
        private Long chengJi;
        private Integer age;
        private BigDecimal value;

    }
    @Test
    public void lambda() {
        List<Student> studentList = new ArrayList();
        studentList.add(new Student("a","am",1L,2,new BigDecimal(3)));
        studentList.add(new Student("a","am1",1L,2,new BigDecimal(3)));
        studentList.add(new Student("b","bm1",1L,2,new BigDecimal(3)));
        List<Student> collect = studentList.stream().collect(Collectors.groupingBy(Student::getCode,
                Collectors.reducing((sum, s) ->
                        new Student(s.code, s.name, sum.chengJi + sum.chengJi,
                                sum.age + s.age, sum.value.add(s.value)))
        )).entrySet().stream().map(c -> c.getValue().get()).collect(Collectors.toList());
        System.out.println(collect);
    }

打印結果:

[OtherTest.Student(code=a, name=am1, chengJi=2, age=4, value=6), OtherTest.Student(code=b, name=bm1, chengJi=1, age=2, value=3)]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM