在java中连接多个迭代器 [英] join multiple iterators in java

查看:489
本文介绍了在java中连接多个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何在Java中加入多个迭代器吗?我找到的解决方案首先迭代一个迭代器,然后继续下一个迭代器。但是,我想要的是当next()被调用时,它首先返回第一个迭代器中的第一个元素。下次调用next()时,它会返回第二个迭代器中的第一个元素,依此类推。

Does anybody know how to join multiple iterators in Java? The solution I found iterate through one iterator first, and then move on to the next one. However, what I want is when next() gets called, it first returns the first element from the first iterator. Next time when next() gets called, it returns the first element from the second iterator, and so on.

谢谢

推荐答案

使用番石榴 AbstractIterator

final List<Iterator<E>> theIterators;
return new AbstractIterator<E>() {
  private Queue<Iterator<E>> queue = new LinkedList<Iterator<E>>(theIterators);
  @Override protected E computeNext() {
    while(!queue.isEmpty()) {
      Iterator<E> topIter = queue.poll();
      if(topIter.hasNext()) {
        E result = topIter.next();
        queue.offer(topIter);
        return result;
      }
    }
    return endOfData();
  }
};

这将为您提供所需的交错订单,它足够聪明,可以处理不同的集合尺寸,而且非常紧凑。 (您可能希望使用 ArrayDeque 代替 LinkedList 获取速度,假设您使用的是Java 6+。)

This will give you the desired "interleaved" order, it's smart enough to deal with the collections having different sizes, and it's quite compact. (You may wish to use ArrayDeque in place of LinkedList for speed, assuming you're on Java 6+.)

如果你真的,真的不能容忍另一个第三方库,你可以或多或少地做一些额外的工作同样的事情,如:

If you really, really can't tolerate another third-party library, you can more or less do the same thing with some additional work, like so:

return new Iterator<E>() {
  private Queue<Iterator<E>> queue = new LinkedList<Iterator<E>>(theIterators);
  public boolean hasNext() {
    // If this returns true, the head of the queue will have a next element
    while(!queue.isEmpty()) {
      if(queue.peek().hasNext()) {
        return true;
      }
      queue.poll();
    }
    return false;
  }
  public E next() {
    if(!hasNext()) throw new NoSuchElementException();
    Iterator<E> iter = queue.poll();
    E result = iter.next();
    queue.offer(iter);
    return result;
  }
  public void remove() { throw new UnsupportedOperationException(); }
};

作为参考,也可以使用all iter1,all iter2等行为来获取 Iterators.concat(Iterator< Iterator>) 及其重载。

For reference, the "all of iter1, all of iter2, etc" behavior can also be obtained using Iterators.concat(Iterator<Iterator>) and its overloads.

这篇关于在java中连接多个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆