【问题标题】:Create Map<String, List<Object>> where the elements of the lists are sorted, using Stream API创建 Map<String, List<Object>> 使用 Stream API 对列表的元素进行排序
【发布时间】:2020-08-31 13:14:50
【问题描述】:

我有任何ArrayList 的“监视器”对象。每个对象都有两个字段,“brand::String”和“price::BigDecimal”。我正在使用以下 Stream 将 Monitor 对象分类为 HashMap&lt;String, List&lt;Monitor&gt;&gt;,其中 key 是名称(因此具有相同名称的监视器最终会出现在同一个列表中:

Map<String, List<Monitor>> monitorsByNameMap =
    monitors.stream()
        .collect(Collectors.groupingBy(Monitor::getName));

我希望根据每个 Monitor 对象的 priceHashMap 中的每个 List&lt;Monitor&gt; 进行排序 - 最好按升序排列。我想知道是否可以通过添加到上面的表达式来实现。

【问题讨论】:

    标签: java java-8 functional-programming java-stream


    【解决方案1】:

    name分组后可以使用collectingAndThen

    Map<String, List<Monitor>> monitorsByNameMap = monitors.stream()
                      .collect(Collectors.groupingBy(Monitor::getName,
                            Collectors.collectingAndThen(Collectors.toList(),
                                  l -> l.stream()
                                           .sorted(Comparator.comparing(Monitor::getPrice))
                                           .collect(Collectors.toList())
                                ))
                        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多