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?
If you find the .*sum() solution above a tad confusing to read (very nice though) you can also do this:
Of course it allows for more complex calculations than just summing.
Prototype (JavaScript framework) has a method
zip()
that does exactly what you need. That doesn't help you though, I know. Funny, I would have expected Groovy to have something similar, but I could not find anything in either theCollection
orList
class.Anyway, here is a not-too-pretty implementation of
zip()
:And here it is in action:
Output:
Of course you can also do it in a less generic way if you want to solve exactly your problem (and not implement a generic zip/map function) :
In most functional programming languages, this is done by using a
map2
(ocaml) orzipWith
(haskell) function, with for example:I didn't find any equivalent in the groovy documentation, but apparently, you can easily define
zipWith
(found at http://cs.calstatela.edu/wiki/index.php/Courses/CS_537/Summer_2008/Chapter_4._Collective_Groovy_datatypes):Groovy's
List.transpose()
works likezip
in some other languages. Try this:I don't know of a built-in solution, but here's a workaround using
collect
and the JavaQueue
'spoll()
method: