使用公共键的值从两个映射创建列表列表

时间:2016-11-15 09:57:43

标签: groovy

有两种不同的地图。一个比另一个大。小地图的键始终是较大地图的键的子集。我想获取两个映射共有的键的值,并使用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]]

1 个答案:

答案 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