Question:
How to merge the maps while summing up values of common keys among the maps.
Input:
[a: 10, b:2, c:
Here is a simple solution that collects the unique keys, the values for each key as an array, and applies the lambda to the array of values for each key. In this first one the lambda takes an array:
def process(def myMaps, Closure myLambda) {
return myMaps.sum { it.keySet() }.collectEntries { key ->
[key, myLambda(myMaps.findResults { it[key] })]
}
}
def map1 = [a: 10, b:2, c:3]
def map2 = [b:3, c:2, d:5]
def maps = [map1, map2]
def sumResult = process(maps) { x -> x.sum() }
def prodResult = process(maps) { x -> x.inject(1) { a, b -> a * b } }
def minResult = process(maps) { x -> x.inject(x[0]) { a, b -> a < b ? a : b } }
assert sumResult == [a:10, b:5, c:5, d:5]
assert prodResult == [a:10, b:6, c:6, d:5]
assert minResult == [a:10, b:2, c:2, d:5]
In this 2nd version the lambda expression takes two values:
def process(def myMaps, Closure myLambda) {
return myMaps.sum { it.keySet() }.collectEntries { key ->
[key, { x ->
x.subList(1, x.size()).inject(x[0], myLambda)
}(myMaps.findResults { it[key] })]
}
}
def map1 = [a: 10, b:2, c:3]
def map2 = [b:3, c:2, d:5]
def maps = [map1, map2]
def sumResult = process(maps) { a, b -> a + b }
def prodResult = process(maps) { a, b -> a * b }
def minResult = process(maps) { a, b -> a < b ? a : b }
assert sumResult == [a:10, b:5, c:5, d:5]
assert prodResult == [a:10, b:6, c:6, d:5]
assert minResult == [a:10, b:2, c:2, d:5]