+-
java-合并多级HashMap的最快方法
我有许多多层HashMap,其中最深的元素是List.级别数可能会有所不同.

直观地说,第一个哈希图是

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

第二个哈希图是

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

合并后应该成为

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

合并它们的最佳方法是什么?一次迭代两个地图并合并将是一个好主意吗?

最佳答案
我首先会使用一个真正有效的版本,然后查看是否需要更快的版本.

可能的解决方案是采用类似以下的递归方法(删除了泛型和强制类型转换以便于阅读):

// 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的最快方法 - 乐贴网