Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Prototype (JavaScript framework) has a <a href="http://www.prototypejs.org/api/enumerable/zip" rel="nofollow">method <code>zip()</code></a> 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 the <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html" rel="nofollow"><code>Collection</code></a> or <a href="http://groovy.codehaus.org/groovy-jdk/java/util/List.html" rel="nofollow"><code>List</code></a> class.</p> <p>Anyway, here is a not-too-pretty implementation of <code>zip()</code>:</p> <pre><code>List.metaClass.zip = { List other, Closure cl -&gt; List result = []; Iterator left = delegate.iterator(); Iterator right = other.iterator(); while(left.hasNext()&amp;&amp; right.hasNext()){ result.add( cl.call(left.next(), right.next()) ); } result; } </code></pre> <p>And here it is in action:</p> <pre><code>def list1 = [1, 1, 1] def list2 = [1, 1, 1] print (list1.zip(list2) {it1, it2 -&gt; it1 + it2}) </code></pre> <p>Output:</p> <blockquote> <p>[2, 2, 2]</p> </blockquote> <hr> <p>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) :</p> <pre><code>List.metaClass.addValues = { List other -&gt; List result = []; Iterator left = delegate.iterator(); Iterator right = other.iterator(); while(left.hasNext()&amp;&amp; right.hasNext()){ result.add( left.next() + right.next() ); } result; } def list1 = [1, 1, 1] def list2 = [1, 1, 1] print (list1.addValues(list2)) // Output again: [2, 2, 2] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload