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

gho*_*der 9 java collections java-8 java-stream

我想转换:

Map<String, Map<String, List<Map<String, String>>>> inputMap 
Run Code Online (Sandbox Code Playgroud)

到:

Map<String, Map<String, CustomObject>> customMap
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

Jac*_* G. 2

一种解决方案是流式传输entrySetof inputMap,然后使用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())));
        }));
Run Code Online (Sandbox Code Playgroud)

  • @SHoko 是的,但我认为如果没有这个块,它看起来会不太可读。 (3认同)