【问题标题】:How to get object field for max value in another field in grouped by one more field?如何在由另一个字段分组的另一个字段中获取最大值的对象字段?
【发布时间】:2022-01-13 17:40:49
【问题描述】:

我的实体列表如下所示:

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

对于每个具有最大版本的代码,我想获取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()));

【问题讨论】:

    标签: java java-stream java-11


    【解决方案1】:

    你可以这样做:

    按每个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))));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      相关资源
      最近更新 更多