有两种不同的地图。一个比另一个大。小地图的键始终是较大地图的键的子集。我想获取两个映射共有的键的值,并使用Groovy功能创建列表列表。目标是使用Groovy功能以尽可能少的代码实现它。
Map big = ['FirstName':'first_name', 'LastName':'last_name', 'FullName':'full_name']
Map small = ['FirstName':'John', 'FullName':'John Williams']
println输出
[[first_name, John], [full_name, John Williams]]
答案 0 :(得分:3)
//works even if the small map is not a subset completely
def result = []
big.keySet().intersect(small.keySet()).each {
result << [big[it], small[it]]
}
assert [['first_name', 'John'], ['full_name', 'John Williams']] == result
编辑: 为 @taiyebur 建议的解决方案添加了两种变体
// VARIATION 2
def result2 = big.subMap(small.keySet()).collect([]) {
[it.value, small.get(it.key)]
}
assert [['first_name', 'John'], ['full_name', 'John Williams']] == result2
// VARIATION 3
def result3 = small.collect([]) {
[big[it.key], it.value]
}
assert [['first_name', 'John'], ['full_name', 'John Williams']] == result3