考虑这个解决方案,虽然它有点脆弱(例如,当键不对齐时)。此外,这会将“第一个”列表修改为副作用,这有点异味。
// 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