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 ?
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.
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.
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.
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
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With