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

我正在尝试更新内部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);

最佳答案

您将忽略内部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);
发布了540 篇原创文章 · 获赞 0 · 访问量 1981

猜你喜欢

转载自blog.csdn.net/weixin_44109689/article/details/103916966