2017-09-05 38 views
2

我有很多Multilevel哈希映射,其中最深的元素是List。级别数量可能会有所不同。最快的方式来合并多级哈希映射

直观地让我们说第一个HashMap的是

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

和第二HashMap的是

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

合并后,它应该成为

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

什么是合并它们的最好方法?只需一次迭代两张地图,并结合起来就是个好主意?

+0

你有Map ? – ByeBye

+0

是的,它是地图<字符串,对象> –

+1

声明的打字没有什么帮助。是否有最大数量的嵌套级别? –

回答

2

我会先与一个真正有效的版本一起使用,然后看看我是否需要更快的版本。

一个可能的解决方案是一个递归方法是这样的(除去泛型和投射更容易读):

// 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)); 
     } 
    } 
} 

只注意到拉姆达标签。我没有看到在这里使用流的理由。把它转换成流,只会让我觉得更复杂。

+0

这是一个整洁的解决方案。值得一提的是,mapLeft拥有最终值 –

+0

@PujanSrivastava我已经添加了关于修改参数的评论。感谢您提出的编辑。我有点担心添加mapLeft作为返回值。如果一个方法返回一个对象,我会期望一个复制/新对象。我认为现在这种方法的意图更加清晰。 –