Java 8, lambda: sort in the grouping list and combine all into the list

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

How to use study_ ID sorts each group, and then through study_ Location returns a list containing all students as the result of grouping, and then press study_ ID sort?

It would be great to use it as an extension of an existing lambda expression:

Map<String,List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need to group based on the order of the elements in the original list

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726,"John","New York"
4321,"Max","California"
2234,"Andrew","Los Angeles"
5223,"Michael","New York"
7765,"Sam","California"
3442,"Mark","New York"

The results will be as follows:

List<Student> groupedAndSorted = ....

    1726,"New York"
    3442,"New York"
    5223,"New York"
    4321,"California"
    7765,"California"
    2234,"Los Angeles"

I have tried the following methods:

studlistGrouped.entrySet().stream().sorted(Comparator.compar‌​ing(Map.Entry::getVa‌​lue))

But it doesn't work

Solution

If I find you right, you need a list < student > (not a map). Students are grouped by their location and sorted by the ID in the group. The groups in the group are also sorted by ID, not by location name This is possible, but requires one grouping and two sorting:

//first,use your function to group students
Map<String,List<Student>> studlistGrouped = students.stream()
        .collect(Collectors.groupingBy(Student::getLocation,Collectors.toList()));

//then sort groups by minimum id in each of them
List<Student> sorted = studlistGrouped.entrySet().stream()
        .sorted(Comparator.comparing(e -> e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
        //and also sort each group before collecting them in one list
        .flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());

This will produce the following results:

Student{id='1726',name='John',location='New York'}
Student{id='3442',name='Mark',location='New York'}
Student{id='5223',name='Michael',location='New York'}
Student{id='2234',name='Andrew',location='Los Angeles'}
Student{id='4321',name='Max',location='California'}
Student{id='7765',name='Sam',location='California'}

Maybe this can be done more gracefully. Suggestions are welcome

Editor: when writing this answer, there is no mention of grouping based on the order of elements in the original list in the OPS question So my assumption is to classify lists and groups by ID For solutions based on the order in the original list, see other answers, for example, holgers one

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>