如何在groovy中合并两张地图 [英] How to merge two maps in groovy

查看:257
本文介绍了如何在groovy中合并两张地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

如何合并地图中的常用键值。



输入:

  [a :10,b:2,c:3] 
[b:3,c:2,d:5]

输出

  [a:10,b:5,c: 5,d:5] 

扩展问题:

如何合并原始2个地图,方法是对2个地图中的公共密钥的值应用函数(Closure)。即不是简单地总结常用键的值,而是让用户指定要使用的函数。



例如:如果用户想要使用'min'功能,而不是总和,那么可以指定min作为结果得到 [a:10,b:2,c:2,d:5]

$ b $



<$> p $ p $ map1 = [a:10,b:2,c:3]
map2 = [b:3,c:2,d:5]
(map1 .keySet()+ map2.keySet())
.inject([:]){m,k - > m [k] =(map1 [k]≠0)+(map2 [k]≠0)。 m}

计算结果为

  [a:10,b:5,c:5,d:5] 

或者,您可以使用collectEntries(封闭不像这样丑):

  map1 = [a:10 ,b:2,c:3] 
map2 = [b:3,c:2,d:5]
(map1.keySet()+ map2.keySet())
。 collectEntries {[(it):( map1 [it]?:0)+(map2 [it]?:0)]}

为了使这个通用,允许传入一个闭包。但collectEntries已经允许,你不会获得太多收益。

Question:
How to merge the maps while summing up values of common keys among the maps.

Input:

[a: 10, b:2, c:3]  
[b:3, c:2, d:5] 

Output

[a:10, b:5, c:5, d:5]

Extended Question:
How to merge the original 2 maps, by applying a function (Closure) on the values of the common keys in the 2 maps. i.e.. instead of simply summing up the values of common keys let the user specify the function to use.

For eg: if user wants to use 'min' function instead of summing, then one can specify min to get [a:10, b:2, c:2, d:5] as the result.

解决方案

You could use inject with ?: for when the map's value for the key is null:

map1 = [a:10, b:2, c:3]
map2 = [b:3, c:2, d:5]
(map1.keySet() + map2.keySet())
    .inject([:]) {m, k -> m[k] = (map1[k] ?: 0) + (map2[k] ?: 0); m }

which evaluates to

[a:10, b:5, c:5, d:5]

Alternatively you can use collectEntries (the closure is not as ugly this way):

map1 = [a:10, b:2, c:3]
map2 = [b:3, c:2, d:5]
(map1.keySet() + map2.keySet())
    .collectEntries {[(it) : (map1[it] ?: 0) + (map2[it] ?: 0)]}

To make this generic, allow passing in a closure. But collectEntries already allows that, you don't gain much.

这篇关于如何在groovy中合并两张地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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