Sort and group by and find max of each group in Java 8

Shraddha :

I have an object which has a name and a score. I want to sort the elements by name and find the max score for that name.

For example below are the objects (name, score):

(a, 3)
(a, 9)
(b, 7)
(b, 10)
(c, 8)
(c, 3)

The output should be:

(a, 9)
(b, 10)
(c, 8)

I am able to sort using the below code, but I am not able to find out max

List<Record> result = list.stream()
        .sorted(Comparator.comparing(Record::score))
        .collect(Collectors.groupingBy(Record::name, LinkedHashMap::new, Collectors.toList()))
        .values().stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
Eran :

You need to chain maxBy to the groupinhBy collectior:

Map<String,Record> result = 
    list.stream()
        .sorted(Comparator.comparing(Record::score))
        .collect(Collectors.groupingBy(Record::name, 
                                       LinkedHashMap::new,
                                       Collectors.maxBy(Comparator.comparing(Record::getScore))));

And if you only care about the Record instances, you can obtain the values() of that Map.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122785&siteId=1