gpt4 book ai didi

java - map 的 map ,如何更新内部 map Java 8的 key

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:46 25 4
gpt4 key购买 nike

我正在尝试更新内部 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,无法理解为什么。在此,我在顶层 map 上调用收集并在供应商 HashMap::new 中收集结果,在累加器中我在内部 map 上调用另一个收集,我在 TreeMap 中收集,现在我希望在顶层 map 中组合累加器输出使用那里提供的 HashMap::putAll 组合器。

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);

关于java - map 的 map ,如何更新内部 map Java 8的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56243910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com