地图的地图,如何更新内部地图的键Java8
我正在尝试更新内部映射中的键,这是顶级映射的值,为此 我在这里给出了3个代码片段,前两个正在工作,并试图理解为什么第三个不工作 这是mapOfMap变量的结构,可以用实类替换已分类的键值地图的地图,如何更新内部地图的键Java8,java,java-8,java-stream,Java,Java 8,Java Stream,我正在尝试更新内部映射中的键,这是顶级映射的值,为此 我在这里给出了3个代码片段,前两个正在工作,并试图理解为什么第三个不工作 这是mapOfMap变量的结构,可以用实类替换已分类的键值 Map<TopLevelMapKey, Map<InnerMapKey, InnerMapValue>> mapOfMap; 这是第二个版本,可能是这里最好的方法,也很好用 mapOfMap .entrySet() .stream() .forEach(topM
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 ))
));
这一个不工作,它返回空地图,无法理解为什么。
在本文中,我调用了collect over top level Map,并在supplier HashMap::new中调用了collect over Internal Map,我在TreeMap中收集了一个collect over Internal Map,现在我希望使用这里提供的HashMap::putAll组合器将累加器的输出组合到顶级Map中
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);
mapOfMap.entrySet().stream()
.collect(HashMap::new,
(hashMap,topMap)->{
TreeMap value=topMap.getValue()
.entrySet().stream()
.collect(树映射::新建,
(treeMap,innerMap)->treeMap.put(innerMap.getKey().getUpdatedKey(),innerMap.getValue()),
树映射::putAll);
put(topMap.getKey(),value);
},
HashMap::putAll);
什么是合并
,您的结果数据结构是什么?无论如何,您都忽略了最后一种方法的内部收集
(流)操作的结果。您当前的操作看起来非常简单,只需使用Map.forEach
asmapOfMap.forEach((ok,ov)->ov.forEach((ik,iv)->{ov.merge(ik.getUpdatedKey(),iv,(val1,val2)->{抛出新的AlcyoneRuntimeException(“合并中的异常,不允许重复”);}); }));代码>