在Groovy中添加两个地图,同时总结公共密钥的值 [英] Add two maps in Groovy while summing up values for common keys

查看:145
本文介绍了在Groovy中添加两个地图,同时总结公共密钥的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Groovy中有两张地图 [a:1,b:2] [b:1,c:3] 并希望从他们创建第三张地图 [a:1,b:3,c:3] 。有没有一个Groovy命令?



编辑:请注意,第三个地图中的值是前两个地图,如果密钥是相同的。



谢谢

解决方案

另一个解决方案是:

  def m1 = [a:1,b:2] 
def m2 = [b:1,c:3]

def newMap = [m1,m2] *。keySet()。flatten()。unique()。collectEntries {
[(it) [m1,m2] *。get(it).findAll()。sum()]
}

流行病人的回答作为灵感,您还可以编写一个方法来处理多个地图

  def m1 = [a:1,b:2] 
def m2 = [b:1,c:3]

def combine(Map ... m){
m.collectMany {it.entrySet()} .inject([:]){result,e - >
结果<< [(e.key):e.value +(result [e.key]?:0)]
}
}

def newMap = combine(m1,m2)


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 Groovy command that does that?

Edit: Notice that the values in the third map, are a sum of the values from the first two maps, if the keys are identical.

Thanks

解决方案

Yet another solution would be:

def m1 = [ a:1, b:2 ]
def m2 = [ b:1, c:3 ]

def newMap = [m1,m2]*.keySet().flatten().unique().collectEntries {
  [ (it): [m1,m2]*.get( it ).findAll().sum() ]
}

Taking epidemian's answer as inspiriation, you can also write a method to handle multiple maps

def m1 = [a: 1, b: 2]
def m2 = [b: 1, c: 3]

def combine( Map... m ) {
  m.collectMany { it.entrySet() }.inject( [:] ) { result, e ->
    result << [ (e.key):e.value + ( result[ e.key ] ?: 0 ) ]
  }
}

def newMap = combine( m1, m2 )

这篇关于在Groovy中添加两个地图,同时总结公共密钥的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆