合并多级哈希图的最快方法



我有许多多级哈希图,其中最深元素列为列表。水平数可能会有所不同。

直观地说,首先是hashmap是

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

和第二hashmap是

{
    "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标签。我看不到这里使用流的理由。在我看来,将其转换为流会使它变得更加复杂。

最新更新