gpt4 book ai didi

java - 迭代和复制HashMap值的有效方法

转载 作者:行者123 更新时间:2023-12-01 09:38:51 25 4
gpt4 key购买 nike

我要转换:

Map<String, Map<String, List<Map<String, String>>>> inputMap 

至:
Map<String, Map<String, CustomObject>> customMap

config中提供了 inputMap,它已经准备就绪,但是我需要 customMap格式。 CustomObject将使用函数中的几行代码从 List<Map<String, String>>派生。

我尝试了一种迭代输入映射并在customMap中复制键值的常规方法。是否有使用Java 8或其他快捷方式进行此操作的有效方法?
Map<String, Map<String, List<Map<String, String>>>> configuredMap = new HashMap<>();
Map<String, Map<String, CustomObj>> finalMap = new HashMap<>();


for (Map.Entry<String, Map<String, List<Map<String, String>>>> attributeEntry : configuredMap.entrySet()) {
Map<String, CustomObj> innerMap = new HashMap<>();
for (Map.Entry<String, List<Map<String, String>>> valueEntry : attributeEntry.getValue().entrySet()) {
innerMap.put(valueEntry.getKey(), getCustomeObj(valueEntry.getValue()));
}
finalMap.put(attributeEntry.getKey(), innerMap);
}

private CustomObj getCustomeObj(List<Map<String, String>> list) {
return new CustomObj();
}

最佳答案

一种解决方案是流entrySetinputMap,然后使用 Collectors#toMap 两次(一次用于外部Map,一次用于内部Map):

Map<String, Map<String, CustomObj>> customMap = inputMap.entrySet()
.stream()
.collect(Collectors.toMap(Function.identity(), entry -> {
return entry.getValue()
.entrySet()
.stream()
.collect(Collectors.toMap(Function.identity(),
entry -> getCustomeObj(entry.getValue())));
}));

关于java - 迭代和复制HashMap值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60671390/

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