stream分组求和

如何用Streamapi进行分组求和,可以使用Collectors.groupby(**, Collectors.summingInt(**))来进行分组求和。

          

public class Test {

    public static void main(String[] args) {

        Student student1 = new Student(1, 1);
        Student student2 = new Student(1, 1);
        Student student3 = new Student(2, 2);
        Student student4 = new Student(2, 3);
        Student student5 = new Student(3, 3);
        Student student6 = new Student(3, 4);
        Student student7 = new Student(4, 1);

        List list = Arrays.asList(student1, student2, student3, student4, student5, student6, student7);

        Map collect = list.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summingInt(Student::getScore)));
        System.out.println(collect);
    }
}

class Student{

    private Integer id;

    private Integer score;

    public Integer getId() {
        return id;
    }

    pub

你可能感兴趣的:(java基本知识,java)