Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
like image 754
Shraddha Avatar asked Jun 19 '19 12:06

Shraddha


1 Answers

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.

like image 158
Eran Avatar answered Sep 28 '22 08:09

Eran