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

后端 未结 4 788
盖世英雄少女心
盖世英雄少女心 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 17:07

    You can use Collectors.groupingBy(classifier,mapFactory,downstream) method for this purpose:

    List list = List.of(
            new Student("abc", 30),
            new Student("Abc", 32),
            new Student("ABC", 35),
            new Student("DEF", 40));
    
    Map map = list.stream()
            .collect(Collectors.groupingBy(
                    Student::getStudentName,
                    () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER),
                    Collectors.summingInt(Student::getMarks)));
    
    System.out.println(map); // {abc=97, DEF=40}
    

提交回复
热议问题