主要思路是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)]