合并列表保留订单与groovy

时间:2013-07-25 00:17:19

标签: list groovy

我有两个长列表:

first = [[A, 2, 4, 6], [B, 1, 3, 5]...]
second = [[A, 8, 10, 12], [B, 7, 9, 11]...]

想要合并(订购保留)

first = [[A, 2, 4, 6, 8, 10, 12], [B, 1, 3, 5, 7, 9, 11]...]

(我会在函数调用的每个{}'{}中执行此操作,因此我需要继续合并到'first') 我想我正在寻找某种补充,加上扁平化,但我无法理解。任何帮助将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:4)

如果:

  • 列表始终匹配,以便如果first中有一个'A'记录,second中有一个记录,first中有'B'记录,那么second等中的一个
  • 列表按相同顺序排序

然后你就可以逃脱:

[ first, second ].transpose()*.flatten()*.unique()

答案 1 :(得分:3)

这是一种方法:

def merge(a, b) {
  tmp = b.collectEntries { [it.first(), it.tail()] }
  return a.collect { it + tmp[it.first()] }
}

它生成一个临时的Map,它由第二个列表中每个条目的第一个子条目键入,然后在迭代第一个列表时查找要追加的相应内容。

例如:

A = "A"
B = "B"
​first = [[A, 2, 4, 6], [B, 1, 3, 5]]
second = [[A, 8, 10, 12], [B, 7, 9, 11]]

println merge(first, second)

对于缺少的元素等,它可能会变得更加健壮。

答案 2 :(得分:0)

考虑这个解决方案,虽然它有些脆弱(例如当键不对齐时)。此外,这会将“第一个”列表修改为副作用,这有点气味。

// modifies 'first' as a side-effect
def merge = { def first, def subSecond ->
    def subFirst = first.find { it[0] == subSecond[0] }
    if (subFirst) {
        subFirst.addAll( subSecond[1..subSecond.size()-1] )
    }
}

// tests 

def first = null
def results = null

first = [["A",2,4,6],["B",1,3,5]]
results = []
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6],["B",1,3,5]] == first

first = [["A",2,4,6],["B",1,3,5]]
results = [ ["A",8,10,12] ]
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6,8,10,12],["B",1,3,5]] == first

first = [["A",2,4,6],["B",1,3,5]]
results = [ ["A",8,10,12],["B",7,9,11]  ]
results.each { def subSecond -> merge(first,subSecond) }
assert [["A",2,4,6,8,10,12],["B",1,3,5,7,9,11]] == first