How to merge two maps in groovy

后端 未结 5 1263
予麋鹿
予麋鹿 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 02:51

    Would this suffice?

    Map one = [a:10, b:2, c:3]
    Map two = [b:3, c:2, d:5]
    
    Map mergeOn(Map one, Map two, Closure closure) {
      two.inject([:] << one) { acc, key, val ->
        key in acc.keySet() ? acc[key] = closure(acc[key], val) : acc << [(key): val]
        acc
      }
    }
    
    assert mergeOn(one, two) { a, b -> a + b }          == [a:10, b:5, c:5, d:5]
    assert mergeOn(one, two) { a, b -> a - b }          == [a:10, b:-1, c:1, d:5]
    assert mergeOn(one, two) { a, b -> a * b }          == [a:10, b:6, c:6, d:5]
    assert mergeOn(one, two) { a, b -> Math.max(a, b) } == [a:10, b:3, c:3, d:5]
    assert mergeOn(one, two) { a, b -> Math.min(a, b) } == [a:10, b:2, c:2, d:5]
    

提交回复
热议问题