Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list

后端 未结 9 1307
难免孤独
难免孤独 2021-02-09 04:21

Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the g

9条回答
  •  醉梦人生
    2021-02-09 04:40

    not 100% clear whether you're expected a Map> or just a List, nevertheless here are both solutions:

    imports:

    import static java.util.stream.Collectors.*;
    import java.util.*;
    import java.util.function.Function;
    

    retrieving a Map> where each List contains students sorted by their ids.

    Map> resultSet = studlist.stream()
          .collect(groupingBy(Student::getLocation,
                 mapping(Function.identity(),
                      collectingAndThen(toList(),
                          e -> e.stream().sorted(Comparator.comparingInt(Student::getId))
                                                .collect(toList())))));
    

    on the other hand, if you want to retrieve just a list of Student objects sorted by a given property then it would be a waste of resources to perform a groupingBy, sorted, collect and somehow reduce the map values into a single list. Rather just sort the Student objects within the list providing a sort key i.e.

    studlist.sort(Comparator.comparingInt(Student::getId));
    

    or

    studlist.sort(Comparator.comparing(Student::getLocation));
    

    or depending on whether you want to sort by more than one property then you could do something like shmosel's answer.

提交回复
热议问题