Puj*_*ava 3 java lambda java-8
我有许多多级 HashMap,其中最深的元素是 List。级别数可能会有所不同。
直观地说,第一个哈希图是
{
"com": {
"avalant": {
"api": []
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二个哈希图是
{
"com": {
"google": {
"service": {
"api": []
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
合并后它应该变成
{
"com": {
"avalant": {
"api": []
},
"google": {
"service": {
"api": []
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
合并它们的最佳方法是什么?一次只迭代两张地图并结合是个好主意?
我会首先选择一个真正有效的版本,然后看看我是否需要一个更快的版本。
一个可能的解决方案是像这样的递归方法(删除泛型和强制转换以便于阅读):
// 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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
刚刚注意到 lambda 标签。我没有看到在这里使用流的理由。在我看来,将其转换为流只会使事情变得更加复杂。
| 归档时间: |
|
| 查看次数: |
1150 次 |
| 最近记录: |