Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum the content of 2 list in Groovy

I have two lists in Groovy and need to sum the contents of both.

For example:

list1 = [1,1,1]
list2 = [1,1,1]

I expected this result:

total = [2,2,2]

I try to sum with + operator o .sum method, but I have a concatenation of the lists.

[1, 1, 1, 1, 1, 1]

It's Groovy enough groovy or I need to loop each element of the lists?

like image 950
Arturo Herrero Avatar asked Jan 03 '11 12:01

Arturo Herrero


2 Answers

Groovy's List.transpose() works like zip in some other languages. Try this:

list1 = [1,2,3]
list2 = [4,5,6]
assert [list1, list2].transpose()*.sum() == [5,7,9]
like image 132
ataylor Avatar answered Oct 01 '22 18:10

ataylor


I don't know of a built-in solution, but here's a workaround using collect and the Java Queue's poll() method:

def list1 = [1, 2, 3]
def list2 = [4, 5, 6] as Queue

assert [5, 7, 9] == list1.collect { it + list2.poll() }
like image 34
Christoph Metzendorf Avatar answered Oct 01 '22 17:10

Christoph Metzendorf