在 Groovy 中添加两个映射,同时汇总公共键的值 [英] Add two maps in Groovy while summing up values for common keys
本文介绍了在 Groovy 中添加两个映射,同时汇总公共键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Groovy [a: 1, b: 2]
和 [b:1, c:3]
中有两个映射,我想用它们创建一个第三张地图[a: 1, b: 3, c: 3]
.是否有执行此操作的 Groovy 命令?
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.
谢谢
推荐答案
另一种解决方案是:
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() ]
}
以epidemian's answer为灵感,你也可以写一个方法来处理多张地图
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屋!
查看全文