【问题标题】:Groovy merge two lists?Groovy合并两个列表?
【发布时间】:2011-02-05 14:09:43
【问题描述】:

我有两个列表:

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

我该怎么做?

谢谢。

【问题讨论】:

  • listC 中的 good 后面真的要两个逗号吗?
  • 列表中的元素何时被视为相等?例如,Name 相同但note 不同的元素会发生什么情况?
  • listA 和 listB 是地图,而不是列表
  • 没有唐。 listA 和 listB 是带有地图元素的列表。

标签: list groovy merge


【解决方案1】:

收集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 正在做的事情,这也帮助了我!谢谢!
【解决方案2】:

这个问题的主题有点笼统,所以如果有人来这里寻找“如何在 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

【讨论】:

    【解决方案3】:
    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2012-02-23
      • 2012-12-04
      • 1970-01-01
      • 2014-12-18
      • 2016-01-12
      相关资源
      最近更新 更多