groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Schalk Cronjé <ysb...@gmail.com>
Subject Re: Iterate over 2 lists in a closure?
Date Fri, 02 Oct 2015 09:22:08 GMT
This thread made me think a zip iterator could be a useful addition to 
the language.

   def myList = [1,2,3]
   def myMap = [ a:'b', c:'d', e:'f' ]
   zip(myList,myMap).each { l,m -> println "$l $m" }

Prints out
   1 a=b
   2 c=d
   3 e=f

If one collection is exhausted, whilst the other is not, then just 
return 'null' for the additional items.


On 02/10/2015 09:44, Dinko Srkoč wrote:
> On 1 October 2015 at 19:47, Winnebeck, Jason
> <Jason.Winnebeck@windstream.com> wrote:
>> [...]
>> This also sounds like a zip operation, which took me a really long time to
>> find in Groovy but I recently found it:
>>
>>
>>
>> def letters = ['a', 'b']
>> def numbers = [1, 2]
>>
>> assert ['a1', 'b2'] ==
>>         GroovyCollections.transpose(letters, numbers).collect { it[0] + it[1]
>> }
>>
> There's an easier way to use `transpose`:
>
>    assert ['a1', 'b2'] == [letters, numbers].transpose()*.join('')
>
> Cheers,
> Dinko
>
>>
>> In your case of testing a condition (equality) you can use any method
>> instead of collect.
>>
>>
>>
>> Jason
>>
>>
>>
>> From: Owen Rubel [mailto:orubel@gmail.com]
>> Sent: Thursday, October 01, 2015 1:28 PM
>> To: users@groovy.incubator.apache.org
>> Subject: Re: Iterate over 2 lists in a closure?
>>
>>
>>
>> if(list1.contains(list2) && list2.contains(list1)){ true }
>>
>>
>> Owen Rubel
>> 415-971-0976
>> orubel@gmail.com
>>
>>
>>
>> On Thu, Oct 1, 2015 at 10:22 AM, Les Hartzman <lhartzman@gmail.com> wrote:
>>
>> Hi,
>>
>>
>>
>> I want to know if it's possible to have a closure that can iterate over 2
>> equal length lists? The equivalent of doing list1.each, list2.each { ... },
>> where each list is a list of an user-defined type.
>>
>>
>>
>> Basically I want to compare elements in the lists to see if they are equal.
>>
>>
>>
>> Thanks.
>>
>>
>>
>> Les
>>
>>
>>
>>
>>
>> ________________________________
>> This email message and any attachments are for the sole use of the intended
>> recipient(s). Any unauthorized review, use, disclosure or distribution is
>> prohibited. If you are not the intended recipient, please contact the sender
>> by reply email and destroy all copies of the original message and any
>> attachments.


-- 
Schalk W. Cronjé
Twitter / Ello / Toeter : @ysb33r


Mime
View raw message