gpt4 book ai didi

groovy - 如何在groovy中合并两个 map

转载 作者:行者123 更新时间:2023-12-04 17:07:45 28 4
gpt4 key购买 nike

问题:
如何在汇总 map 之间的公共(public)键值的同时合并 map 。

输入:

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

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

扩展问题:
如何通过对 2 个映射中的公共(public)键的值应用函数(闭包)来合并原始 2 个映射。即,不是简单地总结公共(public)键的值,而是让用户指定要使用的功能。

例如:如果用户想使用“min”函数而不是求和,那么可以指定 min 得到 [a:10, b:2, c:2, d:5]作为结果。

最佳答案

这是一个简单的解决方案,它收集唯一键、每个键的值作为数组,并将 lambda 应用于每个键的值数组。在第一个中,lambda 采用一个数组:

def process(def myMaps, Closure myLambda) {
return myMaps.sum { it.keySet() }.collectEntries { key ->
[key, myLambda(myMaps.findResults { it[key] })]
}
}

def map1 = [a: 10, b:2, c:3]
def map2 = [b:3, c:2, d:5]

def maps = [map1, map2]

def sumResult = process(maps) { x -> x.sum() }
def prodResult = process(maps) { x -> x.inject(1) { a, b -> a * b } }
def minResult = process(maps) { x -> x.inject(x[0]) { a, b -> a < b ? a : b } }

assert sumResult == [a:10, b:5, c:5, d:5]
assert prodResult == [a:10, b:6, c:6, d:5]
assert minResult == [a:10, b:2, c:2, d:5]
在第二个版本中,lambda 表达式有两个值:
def process(def myMaps, Closure myLambda) {
return myMaps.sum { it.keySet() }.collectEntries { key ->
[key, { x ->
x.subList(1, x.size()).inject(x[0], myLambda)
}(myMaps.findResults { it[key] })]
}
}

def map1 = [a: 10, b:2, c:3]
def map2 = [b:3, c:2, d:5]

def maps = [map1, map2]

def sumResult = process(maps) { a, b -> a + b }
def prodResult = process(maps) { a, b -> a * b }
def minResult = process(maps) { a, b -> a < b ? a : b }

assert sumResult == [a:10, b:5, c:5, d:5]
assert prodResult == [a:10, b:6, c:6, d:5]
assert minResult == [a:10, b:2, c:2, d:5]

关于groovy - 如何在groovy中合并两个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267591/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com