How to get object field for max value in another field in grouped by one more field?
I have list of entities that looks like this:
class History {
public String code;
public Integer version;
public LocalDateTime creationDate;
}
For each code with max version I wanna to get creationDate. I did it like this, but I think that it can be done somehow easier...
Map<String, History> historyMaxVersion = histories.stream()
.collect(Collectors.toMap(History::getCode, Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(History::getVersion))));
Map<String, LocalDateTime> historiesLastUpdatedDates = historyMaxVersion.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()
.getCreationDate()));
Solution 1:
You can do like this:
After grouping by each code
then use collectingAndThen
collectors and find max item based on version
amount and at the end use map
to extract creationCode
.
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.maxBy;
Map<String, LocalDateTime> result = histories.stream()
.collect(Collectors.groupingBy(History::getCode,
collectingAndThen(maxBy(Comparator.comparing(History::getVersion)),
history -> history.map(History::getCreationDate).orElse(null))));