Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge maps with recursive nested maps in Groovy

Tags:

java

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 ?

like image 746
eVoxmusic Avatar asked Dec 14 '14 22:12

eVoxmusic


People also ask

How to merge 2 maps in Groovy?

The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.

Can we merge two maps?

The Map. putAll() method provides a quick and simple solution to merge two maps. This method copies all key-value pairs from the second map to the first map. Since a HashMap object can not store duplicate keys, the Map.

How do I merge maps?

concat() Alternatively, we can use Stream#concat() function to merge the maps together. This function can combine two different streams into one. As shown in the snippet, we are passed the streams of map1 and map2 to the concate() function and then collected the stream of their combined entry elements.


1 Answers

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
]
like image 185
dmahapatro Avatar answered Sep 24 '22 05:09

dmahapatro