Search code examples
javagroovy

Merge maps with recursive nested maps in Groovy


I would like to know if someone have an easy way to merge 2 deep nested maps together ?

For instance, I would like to get :

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

There is someone having easy solution ?


Solution

  • 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
    ]