Add two maps in Groovy while summing up values for common keys

前端 未结 7 929
花落未央
花落未央 2020-12-16 12:24

I have two maps in Groovy [a: 1, b: 2] and [b:1, c:3] and would like to create from them a third map [a: 1, b: 3, c: 3]. Is there a Gr

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 12:55

    This does it:

    Map additionJoin( Map map1, Map map2 )
    {
      def result = [:];
      result.putAll( map1 );
      result.putAll( map2 );
    
      result.each { key, value ->
        if( map1[key] && map2[key] )
        {
          result[key] = map1[key] + map2[key]
        }
      }
    
      return result;
    }
    
    def a = [a: 1, b: 2]
    def b = [b:1,c:3]
    
    def c = additionJoin( a, b )
    
    println c
    

提交回复
热议问题