在 Groovy 中将地图与递归嵌套地图合并

2022-09-03 05:03:32

我想知道是否有人有一个简单的方法将2个深度嵌套地图合并在一起?

例如,我想得到:

[
    "a" : "1",
    "animals" : ["cat" : "blue"]
] + [
    "b" : 2,
    "animals" : ["dog" : "red"]
] == [
    "a" : 1,
    "b" : 2,
    "animals" : [
        "cat" : "blue",
        "dog" : "red"]
]

有人有简单的解决方案吗?


答案 1

你可以写一个使用递归: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
]

答案 2

我有一个与@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)

推荐