首页 > 解决方案 > 如何对嵌套地图进行分组

问题描述

我目前的尝试:

Map<Integer, Map<String, Integer>> collect = shopping.entrySet()
            .stream()
            .collect(Collectors.toMap/*groupingBy? */(e -> e.getKey().getAge(),
                    e -> e.getValue().entrySet().stream().collect(Collectors.groupingBy(b -> b.getKey().getCategory(), Collectors.summingInt(Map.Entry::getValue)))));

shopping基本上是一张地图:Map<Client, Map<Product,Integer>>

问题来自于提供的数据包含多个键值- 有相同年龄的客户端,代码仅适用于单个键值。

我怎样才能使这个代码也适用于多个键?

我想它应该以某种方式更改为使用 collect collect(Collectors.groupingBy)->

在生成的地图中 Map<Integer, Map<String, Integer>>

我尝试使用 groupingBy:

Map<Integer, Map<String, Integer>> collect = shopping.entrySet()
            .stream()
            .collect(Collectors.groupingBy(/*...*/))

只是我想使用流将该代码重构为一个:

Map<Integer, Map<String, Integer>> counts = new HashMap<>();

 for (Map.Entry<Client, Map<Product, Integer>> iData : shopping.entrySet()) {
      int age = iData.getKey().getAge();
      for (Map.Entry<Product, Integer> iEntry : iData.getValue().entrySet()) {
        String productCategory = iEntry.getKey().getCategory();
        counts.computeIfAbsent(age, (agekey) -> new HashMap<>()).compute(productCategory, (productkey, value) -> value == null ? 1 : value + 1);
      }
    }

标签: javajava-stream

解决方案


forEach转换 for 循环的非流( )方法可能是:

Map<Integer, Map<String, Integer>> counts = new HashMap<>();
shopping.forEach((key, value1) -> value1.keySet().forEach(product ->
        counts.computeIfAbsent(key.getAge(),
                (ageKey) -> new HashMap<>())
                .merge(product.getCategory(), 1, Integer::sum)));

推荐阅读