How to merge two maps in groovy

后端 未结 5 1273
予麋鹿
予麋鹿 2021-01-06 02:32

Question:
How to merge the maps while summing up values of common keys among the maps.

Input:

[a: 10, b:2, c:         


        
5条回答
  •  悲哀的现实
    2021-01-06 03:00

    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]
    

提交回复
热议问题