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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With