2010-04-08 609 views
5

我有两个列表:Groovy合并两个列表?

listA: 
[[Name: mr good, note: good,rating:9], [Name: mr bad, note: bad, rating:5]] 

listB: 
[[Name: mr good, note: good,score:77], [Name: mr bad, note: bad, score:12]] 

我想这一个

listC: 
[[Name: mr good, note: good,, rating:9, score:77], [Name: mr bad, note: bad, rating:5,score:12]] 

我怎么能做到这一点?

感谢。

+1

你真的想在listC中使用两个逗号吗? – John 2010-04-08 07:37:06

+0

什么时候你的列表中的元素被认为是相等的?例如,具有相同'Name'但不同'note'的元素会发生什么? – stefanglase 2010-04-08 11:46:50

+0

listA和listB是地图,而不是列表 – 2010-04-09 00:34:28

回答

4

收集listA中的所有元素,并在listB中找到elementA equivilient。从listB中删除它,并返回组合的元素。

如果说您的结构上面,我可能会做:

def listC = listA.collect({ elementA -> 
    elementB = listB.find { it.Name == elementA.Name } 

    // Remove matched element from listB 
    listB.remove(elementB) 
    // if elementB == null, I use safe reference and elvis-operator 
    // This map is the next element in the collect 
    [ 
     Name: it.Name, 
     note: "${it.note} ${elementB?.note :? ''}", // Perhaps combine the two notes? 
     rating: it.rating?:0 + elementB?.rating ?: 0, // Perhaps add the ratings? 
     score: it.score?:0 + elementB?.score ?: 0 // Perhaps add the scores? 
    ] // Combine elementA + elementB anyway you like 
} 

// Take unmatched elements in listB and add them to listC 
listC += listB 
+0

尽管我并不是想要完成OP所做的事情,但是这帮助了我!谢谢! – djule5 2010-11-03 05:12:49

0

问题的主题是有点一般,所以我会后回答一个simplier问题,如果有人来到这里寻找“如何在Groovy中将两个列表合并成一张地图?”

def keys = "key1\nkey2\nkey3" 
def values = "value1,value2,value3" 
keys = keys.split("\n") 
values = values.split(",") 
def map = [:] 
keys.eachWithIndex() {param,i -> map[keys[i]] = values[i] } 
print map