开发者

Java or Groovy equivalent of python for loop + izip

Does anyone know the java or groovy equivalent of a python for loop us开发者_如何学编程ing 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


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
}


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.


Another option is using FunctionalJava's Zipper:

Provides a pointed stream, which is a non-empty zipper-like stream structure that tracks an index (focus) position in a stream. Focus can be moved forward and backwards through the stream, elements can be inserted before or after the focused position, and the focused item can be deleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜