Map of Map,如何更新内部Map Java 8的键

时间:2019-05-21 17:52:23

标签: java java-8 java-stream

为此,我正在尝试更新内部Map中的键,它是顶级Map的值。 我在这里给出了3个代码段,其中前2个有效,并且试图理解为什么第3个无效。

这是mapOfMap变量的结构,可以将分类的键值替换为真实的类。

Map<TopLevelMapKey, Map<InnerMapKey, InnerMapValue>> mapOfMap;

这是第一个版本,效果很好。

mapOfMap
    .entrySet()
    .stream()
    .forEach(topMap -> map
      .put(topMap.getKey(),
         topMap.getValue()
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                         innerMapEntry -> innerMapEntry.getKey().getUpdatedKey, Map.innerMapEntry::getValue,
                        (v1, v2) -> {
                          throw new RuntimeException(" Exception in merging, duplicates not allowed.");},
                         TreeMap::new))));

这是第二个版本,可能是这里最好的方法,也可以正常工作。

mapOfMap
    .entrySet()
    .stream()
    .collect(Collectors.toMap(Map.Entry::getKey,
                              topMap -> topMap.getValue()
                            .entrySet()
                            .stream()
                            .collect(Collectors.toMap( innerMapEntry -> innerMapEntry.getKey().getUpdatedKey,
                                                        Map.Entry::getValue, 
                                                        v1, v2) -> {
                                                        throw new RuntimeException(" Exception in merging, duplicates not allowed.");}, 
                                                        TreeMap::new ))
        ));

这是行不通的,它返回了空的Map,无法理解原因。 在此,我称收集顶级地图,并在供应商HashMap :: new中收集结果,在累加器中,我又调用另一个在TreeMap中收集的内部地图上的收集,现在我希望将累加器输出合并到顶级Map中使用HashMap :: put在那里提供的所有组合器。

mapOfMap
    .entrySet()
    .stream()
    .collect(HashMap::new,
             (hashMap, topMap) ->
                 topMap.getValue()
                    .entrySet()
                    .stream()
                    .collect( TreeMap::new,
                              (treeMap, innerMap) ->  treeMap.put(innerMap.getKey().getUpdatedKey, innerMap.getValue()),
                               TreeMap::putAll),
             HashMap::putAll);

1 个答案:

答案 0 :(得分:2)

您将忽略内部collect()的返回值。您应该将其放在给定的hashMap值中:

mapOfMap.entrySet().stream()
        .collect(HashMap::new,
                (hashMap, topMap) -> {
                    TreeMap<TopLevelMapKey, InnerMapValue> value = topMap.getValue()
                            .entrySet().stream()
                            .collect(TreeMap::new,
                                    (treeMap, innerMap) -> treeMap.put(innerMap.getKey().getUpdatedKey(), innerMap.getValue()),
                                    TreeMap::putAll);
                    hashMap.put(topMap.getKey(), value);
                },
                HashMap::putAll);
相关问题