我想知道是否有人可以轻松地将两个深层嵌套地图合并在一起?
例如,我想得到:
[
"a" : "1",
"animals" : ["cat" : "blue"]
] + [
"b" : 2,
"animals" : ["dog" : "red"]
] == [
"a" : 1,
"b" : 2,
"animals" : [
"cat" : "blue",
"dog" : "red"]
]
有人有简单的解决方案吗?
答案 0 :(得分:14)
您可以使用递归为Map
编写一个:
Map.metaClass.addNested = { Map rhs ->
def lhs = delegate
rhs.each { k, v -> lhs[k] = lhs[k] in Map ? lhs[k].addNested(v) : v }
lhs
}
def map1 = [
"a" : "1",
"animals" : ["cat" : "blue"]
]
def map2 = [
"b" : 2,
"animals" : ["dog" : "red"]
]
assert map1.addNested( map2 ) == [
a: '1',
animals: [cat: 'blue', dog: 'red'],
b: 2
]
答案 1 :(得分:8)
我有一个与@dmahapatro类似的解决方案,但是使用带有可变参数的方法:
def m1 = [a: 1, animals: [cat: 'blue']]
def m2 = [b: 2, animals: [dog: 'red']]
Map merge(Map... maps) {
Map result
if (maps.length == 0) {
result = [:]
} else if (maps.length == 1) {
result = maps[0]
} else {
result = [:]
maps.each { map ->
map.each { k, v ->
result[k] = result[k] instanceof Map ? merge(result[k], v) : v
}
}
}
result
}
assert [:] == merge()
assert m1 == merge(m1)
assert [a:1, b:2, animals:[cat:'blue', dog:'red']] == merge(m1, m2)
答案 2 :(得分:0)
这是一种非常简短的方法,无需使用元编程:
Map one = ["a" : "1", "animals" : ["cat" : "blue"] ]
Map two = ["b" : "2", "animals" : ["dog" : "red"] ]
Map three = [:]
(one.entrySet() + two.entrySet()).each { entry ->
three[entry.key] = three.containsKey(entry.key) ? [:] << three[entry.key] << entry.value : entry.value
}
println three
呈现输出:
[a:1, animals:[cat:blue, dog:red], b:2]
答案 3 :(得分:0)
另一个类似于@dmahapatro的解决方案,但不使用metaClass:
Map mergeMaps(Map lhs, Map rhs) {
rhs.each { k, v ->
lhs[k] = (lhs[k] in Map ? mergeMaps(lhs[k], v) : v)
}
return lhs
}
def m1 = [a: 1, animals: [cat: 'blue']]
def m2 = [b: 2, animals: [dog: 'red']]
mergeMaps(m1, m2)
println(m1)