【问题标题】:Reorder list containing lists into a map [duplicate]将包含列表的列表重新排序到地图中[重复]
【发布时间】:2020-08-05 20:57:28
【问题描述】:

我有一个List<Item> 类型的变量,其中项目如下所示:

class Item {
    List<Integer> customerId;
}

我想将其重新排序为 Map&lt;Integer, List&lt;Item&gt;&gt;,其中键是 customerId,然后值是具有该客户 ID 的所有项目的列表。

这很容易通过两个 for 循环完成,遍历项目列表,并为每个项目遍历客户列表。

有没有什么方法可以用 Java 流以不同的方式实现这一点,也许是更紧凑的方式?

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    您可以为客户id和Item的每个组合创建Map.Entry,然后使用groupingBy

    Map<Integer,List<Item>> result = list.stream()
               .flatMap(item->item.getCustomerId()
                       .stream()
                       .map(id->Map.<Integer,Item>entry(id,item)))
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                        Collectors.mapping(Map.Entry::getValue,Collectors.toList())));
    

    【讨论】:

      【解决方案2】:

      你可以试试这个方法

      Map<Integer, List<Item>> res = list.stream()
              .flatMap(e -> e.getCustomerId()
                             .stream()
                             .map(id -> new SimpleEntry<Integer, Item>(id, e)))
              .collect(Collectors.groupingBy(k -> k.getKey(),
                  Collectors.mapping(v -> v.getValue(), Collectors.toList())));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        • 2017-04-28
        • 1970-01-01
        • 2020-11-01
        • 2020-08-02
        相关资源
        最近更新 更多