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

后端 未结 9 1305
难免孤独
难免孤独 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:41

    You don't need to group by location, as the input and output have same datatype. You can just chain multiple Comparators and sort the input.

    List groupedAndSorted = studlist.stream()
           .sorted(Comparator.comparing(Student::getStudLocation)
                    .thenComparing(Comparator.comparing(Student::getStudId)))
                    .thenComparing(Comparator.comparing(Student::getStudName)))
           .collect(Collectors.toList());
    

    As an offtopic, I would seggest that you change you data structure to use Lombok to auto-generate getters/setters/constructors https://projectlombok.org/features/Data . You should also use a more generic naming conversion, i.e. remove the "stud_" prefix of attributes.

    import lombok.Data;
    @Data
    class Student {
        String id;
        String name;
        String location;
    }
    

提交回复
热议问题