views:

73

answers:

2

Hi,

Does anyone know the java or groovy equivalent of a python for loop using izip?

python example:

for item_one, item_two in izip(list_one, list_two):

I'd like to do the same in java or groovy

Thanks

A: 

The closest equivalent in Java would be (assuming that both the lists have same length/size)

Object item_one, item_two;
for (int i=0; i<list_one.length; i++)
{
    item_one = list_one.get(i);
    item_two = list_two.get(i);
}

i.e., you will have to iterate simultaneously over the lists. This is just one example, it can be done with iterators as well.

Faisal Feroz
The groovy equivalent of this one is list_one.eachWithIndex {one, i -> two = list_two[i]; }
Blacktiger
@Faisal - sorry I should have been more clear...I knew that but wanted something better.
dotnetnewbie
@Blacktiger -- I'll try it out thx
dotnetnewbie
+1  A: 

I don't think groovy has an equivalent to izip built in, but here is one possible implementation:

def izip(iters) {
    return [
        hasNext: { -> iters.every{it.hasNext()} }, 
        next: { -> iters.collect{it.next()} }, 
        remove: { -> }
    ] as Iterator
}

list_one = [1,2,3]
list_two = ['a', 'b', 'c']

izip([list_one.iterator(), list_two.iterator()]).each {
    println it
}
ataylor