list - Groovy 合并两个列表?

标签 list groovy merge

我有两个 list :

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]] 

我怎么办?

谢谢。

最佳答案

收集listA中的所有元素,并在listB中找到等价的elementA。从 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 

关于list - Groovy 合并两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2598152/

相关文章:

list - (wx)最大: how to iterate an action over every member of a list?

我可以对 2 个不同的结构使用相同的指针吗?

c - 段错误合并排序程序

c# - 将 List<String> 中的所有字符串转换为单个逗号分隔字符串的最佳方法

python - 列表列表和整数列表

grails - 状态为“暂时移动”且无 body

jenkins - 并行任务日志困惑

groovy - 为什么 Class 对象的方法闭包会失败?

SVN 合并 : "Target path does not exist"

r - 如何保留原始列以便在 r 中两个数据库的 full_join() 中进行比较