java - 合并多级 HashMap 的最快方法

标签 java lambda java-8

我有很多多级 HashMap,其中最深的元素是列表。级别数可能会有所不同。

直观地说,第一个 hashmap 是

{
    "com": {
        "avalant": {
            "api": []
        }
    }
}

第二个 HashMap 是

{
    "com": {
        "google": {
            "service": {
                "api": []
            }
        }
    }
}   

合并后应该变成

{
    "com": {
        "avalant": {
            "api": []
        },
        "google": {
            "service": {
                "api": []
            }
        }
    }
}

合并它们的最佳方式是什么?一次只迭代两个 map 并合并是个好主意吗?

最佳答案

我会先选择一个真正有效的版本,然后看看我是否需要更快的版本。

一个可能的解决方案是像这样的递归方法(删除泛型和强制转换以便于阅读):

// after calling this mapLeft holds the combined data
public void merge(Map<> mapLeft, Map<> mapRight) {
    // go over all the keys of the right map
    for (String key : mapRight.keySet()) {
        // if the left map already has this key, merge the maps that are behind that key
        if (mapLeft.containsKey(key)) {
            merge(mapLeft.get(key), mapRight.get(key));
        } else {
            // otherwise just add the map under that key
            mapLeft.put(key, mapRight.get(key));
        }
    }
}

刚刚注意到 lambda 标签。我看不出有理由在这里使用流。在我看来,将其转换为流只会变得更加复杂。

关于java - 合并多级 HashMap 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051062/

相关文章:

java - 我如何在 Tapestry5 中创建自定义文本字段以将一些 Javascript 呈现到页面上?

c# - Predicates 或 Actions 是否具有任何其他属性或特性以将它们与 Funcs 区分开来?

c++ - 我可以在 lambda 中使用可变参数模板吗?

Java 8 围绕功能作为一等公民跳舞?

Java 内存泄漏 - jmap 不显示类,但 jstat 显示

android - 统一: JDK stop working

Java在ubuntu上找不到文件

java - getResourceAsStream 路径与项目结构相关?

c# - 带有 StartsWith 的 List<string> 的 E.F. lambda 表达式

java - Freemarker:如何使用 Multimap(或列表 map )