简体   繁体   中英

How to grouping and reducing in Java8

As I have List of Subject

"Subjects":[
{"subject":"Math","grades":1},
{"subject":"Math","grades":2},
{"subject":"Math","grades":3},
{"subject":"Math","grades":3},
{"subject":"Lab","grades":10},
{"subject":"Lab","grades":12}
]

I want to grouping and reducing result like this

//Expected Result
"Subjects":[
{"subject":"Math","grades":[1,2,3]},
{"subject":"Lab","grades":[10,12]}
]

I'm curious about How can I Map and reduce Object In java8 Style. I put obsolete code below.

My Main Class

public static void main(String[] args)  {
List<Subject> list = new ArrayList<>();
list.add(new Subject("Math",1));
list.add(new Subject("Math",2));
list.add(new Subject("Math",3));
list.add(new Subject("Math",3));
list.add(new Subject("Lab",10));
list.add(new Subject("Lab",12));        
Map<String, Set<Integer>> result = new HashMap<>();
list.stream().forEach(subjects-> {
    if(result.get(subjects.getSubject())==null){
        Set<Integer> set = new HashSet<>();
        set.add(subjects.getGrades());
        result.put(subjects.getSubject(),set );
    }else{
        Set<Integer> set =result.get(subjects.getSubject());
        set.add(subjects.getGrades());
        result.put(subjects.getSubject(), set);
    }
    });

    result.forEach((key,val)->{
        System.out.println("KEY:"+key + " RESULT :"+val);
    });

}  


public class Subject {
private String subject;
private Integer grades;

public Subject(String subject , Integer grade) {
this.subject = subject;
this.grades = grade;
}

/** get set **/
}

You could use a Collectors.groupingBy(Subject::getSubject) and a Collectors.mapping(Subject::getGrades, Collectors.toSet()) as a downstream.

list.stream()
    .collect(Collectors.groupingBy(Subject::getSubject,
                 Collectors.mapping(Subject::getGrades, 
                     Collectors.toSet())));

It would give you a Map<String, Set<Integer>> .

{Lab=[10, 12], Math=[1, 2, 3]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM