我有很多多级 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/