Merge maps with recursive nested maps in Groovy

You can write one for Map using recursion:

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
]

I had a similar solution as @dmahapatro, but with a method with variable arguments:

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)

Tags:

Java

Groovy