我想检查谁能想出最好的Groovy-sh方式来实现这个目标 -
def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]]
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]]
我想要结果
[["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]]
我目前正在迭代地图并执行此操作。我正在寻找使用Gpath和findAll
的解决方案谢谢, Sreehari。
答案 0 :(得分:3)
您可以transpose
列出每个列表并从每个列表中获取条目(id
或t
):
def fn = { m1, m2 ->
return [m1,m2]
.transpose()
.collect { [ id: it.first().id, t: it.last().t ] }
}
def m1 = [["id":"1","o":"11"],["id":"1","o":"12"],["id":"2","o":"21"]]
def m2 = [["o":"11","t":"t1"],["o":"11","t":"t2"],["o":"21","t":"t1"]]
assert fn(m1, m2) ==
[["id":"1","t":"t1"],["id":"1","t":"t2"],["id":"2","t":"t1"]]
答案 1 :(得分:0)
您可以使用转置将地图压缩成对,然后将这些对组合并按地图键过滤:
[m1, m2]
.transpose()
.collect { (it[0] + it[1]).subMap(['id', 't']) }
评估为
[[id:1, t:t1], [id:1, t:t2], [id:2, t:t1]]
这适用于使用groovy-2.4.4的groovysh,使用jdk7或jdk8。