Groovy如何合并两个列表?

8

我有两个列表:

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

我该如何做到呢?

谢谢。


2
你在 listC 中的 good 后面真的想要两个逗号吗? - John
你的列表中的元素何时被视为相等?例如,具有相同“名称”但不同“注释”的元素会发生什么? - stefanglase
listA和listB是映射,不是列表。 - Dónal
1
listA和listB是带有映射元素的列表。 - sbglasius
3个回答

6

收集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 

尽管我并不是在做与OP完全相同的事情,但这确实帮了我很大的忙!谢谢! - djule5

0
import groovy.util.logging.Slf4j
import org.testng.annotations.Test

@Test
@Slf4j
class ExploreMergeListsOfMaps{
    final def listA = [[Name: 'mr good', note: 'good',rating:9], [Name: 'mr bad', note: 'bad',rating:5]]
    final def listB = [[Name: 'mr good', note: 'good',score:77], [Name: 'mr bad', note: 'bad', score:12]]

    void tryGroupBy() {
        def listIn = listA + listB
        def grouped = listIn.groupBy { item -> item.Name }
        def answer = grouped.inject([], { candidate, item -> candidate += mergeMapkeys( item.value )})
        log.debug(answer.dump())
    }

    private def mergeMapkeys( List maps ) {
        def ret =  maps.inject([:],{ mergedMap , map -> mergedMap << map })
        ret
    }
}

0

问题的主题有些普遍,因此我将回答一个更简单的问题,如果有人在这里寻找“如何在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接