Java Stream - group by when key appears in a list

后端 未结 1 1666
暖寄归人
暖寄归人 2021-01-14 19:35

I am trying to group by a collection by a value that appears in my object as a list.

This is the model that I have

public class Student {
  String s         


        
相关标签:
1条回答
  • 2021-01-14 20:20

    Summing up the comments above, the collected wisdom would suggest:

    Map<String, List<Student>> x = studlist.stream()
                .flatMap(student -> student.getStud_location().stream().map(loc -> new AbstractMap.SimpleEntry<>(loc, student)))
                .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, toList())));
    

    As an alternate approach, if you don't mind the Students in each list containing only that location, you might consider flattening the Student list to Students with only one location:

    Map<String, List<Student>> x = studlist.stream()
            .flatMap( student ->
                    student.stud_location.stream().map( loc ->
                            new Student(student.stud_id, student.stud_name, loc))
            ).collect(Collectors.groupingBy( student -> student.stud_location.get(0)));
    
    0 讨论(0)
提交回复
热议问题