Transform a List<Object> to a Map such that the String is not a duplicate value using Java 8 Streams

后端 未结 4 648
盖世英雄少女心
盖世英雄少女心 2021-01-12 16:02

We have a Student class as follows:

class Student {
    private int marks;
    private String studentName;

    public int getMarks() {
        r         


        
4条回答
  •  走了就别回头了
    2021-01-12 16:54

    That's because of an incorrect merge function, you should instead use:

    Map map = studentList.stream()
            .collect(Collectors.toMap(
                    student -> student.getStudentName().toLowerCase(),
                    Student::getMarks,
                    (s1, s2) -> s1 + s2, // add values when merging
                    LinkedHashMap::new));
    

提交回复
热议问题