如何在另一个字段中获取另一个字段中最大值的对象字段?

How to get object field for max value in another field in grouped by one more field?

我有如下所示的实体列表:

class History {
    public String code;
    public Integer version;
    public LocalDateTime creationDate;
}

对于每个具有最大版本的代码,我想获取创建日期。我是这样做的,但我认为它可以以某种方式更容易地完成...

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()));

你可以这样做:

按每个 code 分组后,然后使用 collectingAndThen 收集器并根据 version 数量找到最大项目,最后使用 map 提取 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))));