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?
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]
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With