Reputation: 3915
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!
Upvotes: 0
Views: 671
Reputation: 24393
I like Will P's answer more, but here's an alternative:
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']
]
Upvotes: 1
Reputation: 14549
You can collect
the head()
, pop()
and 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']
]
Upvotes: 3
Reputation: 24498
Here is one way (clearly needs some defensive checks regarding matching sizes of list1, list2, empty lists, etc):
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
Upvotes: 1
Reputation: 122414
[list1, list2].transpose().collect { [it[0][0]] + it[1] + it[0][1..-1] }
will do what you need but isn't particularly efficient as it creates and then throws away many intermediate lists. The more efficient approach would be good old fashioned direct iteration:
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
}
which is rather less Groovy but creates far fewer throwaway lists.
Upvotes: 1
Reputation: 3694
Try this:
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)
Upvotes: 0