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

前端 未结 7 920
花落未央
花落未央 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:44

    I don't think there's a ready-made method for this, maybe use something like:

    def m1 = [a: 1, b: 2]
    def m2 = [b: 1, c: 3]
    def newMap = (m1.keySet() + m2.keySet()).inject([:]) { 
        acc, k -> acc[k] = (m1[k] ?: 0) + (m2[k] ?: 0); acc 
    }
    

提交回复
热议问题