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

后端 未结 9 1310
难免孤独
难免孤独 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 04:52

    try sort first and then groupinBy it works well. The below code sorts the Students within the location.

    students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation))
    The output in this case is

    {New York=[1726  John  New York, 3442  Mark  New York, 5223  Michael  New York], Los Angeles=[2234  Andrew  Los Angeles], California=[4321  Max  California, 7765  Sam  California]}
    

    If you would like to have locations also to be sorted, use a code snippet like below

    students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation, TreeMap::new, Collectors.toList()))
    

    The output in this case is {California=[4321 Max California, 7765 Sam California], Los Angeles=[2234 Andrew Los Angeles], New York=[1726 John New York, 3442 Mark New York, 5223 Michael New York]}

    Student class implements Comparable and the compareTo method is is based on the id.

提交回复
热议问题