0

I am groovy beginner

I have two lists

    ​list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']....[]...] 

   list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

i want to combine these lists in following format

 list3  = [[1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], [2, 4, '2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']]

tried Groovy: Add some element of list to another list

but couldn't do in this format.. help me!

4

5 回答 5

3

您可以collect,head()pop():tail()

def list1 = [ [1,'Rob','Ben', 'Ni', 'cool'], [2, 'Jack', 'Jo', 'Raj', 'Giri'] ]

def list2 = [ [null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12'] ]

def stack = list2.reverse()

def list3 = list1.collect { l1 -> 
    [l1.head()] + stack.pop() + l1.tail()
}

assert list3 == [
  [1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], 
  [2,4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']
]
于 2013-10-09T12:34:52.087 回答
1

这是一种方法(显然需要对 list1、list2、空列表等的匹配大小进行一些防御性检查):

def list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']] 
def list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

def newList = []

list1.eachWithIndex { def subList1, def index ->
    def tmpList = []
    tmpList << subList1[0]
    tmpList.addAll(list2[index])
    tmpList.addAll(subList1[1..subList1.size()-1])
    newList << tmpList
}

def list3  = [[1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], [2,4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']]

assert newList == list3
于 2013-10-09T11:27:25.560 回答
1

我更喜欢 Will P 的回答,但这里有一个替代方案:

def list1 = [ [1,'Rob','Ben', 'Ni', 'cool'], [2, 'Jack', 'Jo', 'Raj', 'Giri'] ]

def list2 = [ [null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12'] ]

def list3 = []
list1.eachWithIndex { one, i -> list3 << [one[0]] + list2[i] + one[1..-1] }

assert list3 == [
  [1, null, '2013-10-09', '2013-10-10', 'Rob', 'Ben', 'Ni', 'cool'], 
  [2, 4,'2013-10-11', '2013-10-12', 'Jack', 'Jo', 'Raj', 'Giri']
]
于 2013-10-09T13:41:31.697 回答
1
[list1, list2].transpose().collect { [it[0][0]] + it[1] + it[0][1..-1] }

会做你需要的,但不是特别有效,因为它会创建然后丢弃许多中间列表。更有效的方法是老式的直接迭代:

def list3 = []
def it1 = list1.iterator()
def it2 = list2.iterator()
while(it1.hasNext() && it2.hasNext()) {
  def l1 = it1.next()
  def l2 = it2.next()
  def l = [l1[0]]
  l.addAll(l2)
  l.addAll(l1[1..-1])
  list3 << l
}

这是相当少的 Groovy,但创建的一次性列表要少得多。

于 2013-10-09T11:14:42.580 回答
0

尝试这个:

​list1 = [[1,'Rob','Ben', 'Ni', 'cool'],[2,'Jack','Jo','Raj','Giri']....[]...] 
list2 = [[null,'2013-10-09','2013-10-10'],[4, '2013-10-11', '2013-10-12']]

def list3 = []
list3.addAll(list1)
list3.addAll(list2)
于 2013-10-09T11:05:29.453 回答