All Downloads are FREE. Search and download functionalities are using the official Maven repository.

overflowdb.util.MultiIterator Maven / Gradle / Ivy

There is a newer version: 1.173
Show newest version
package overflowdb.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * Subclass-safe variant of MultiIterator from Tinkerpop
 */
public final class MultiIterator implements Iterator, Serializable {

  public static  MultiIterator from(Iterator... iterators) {
    MultiIterator result = new MultiIterator<>();
    for (Iterator iter : iterators) result.addIterator(iter);
    return result;
  }

  private final List> iterators = new ArrayList<>();
  private int current = 0;

  public void addIterator(final Iterator iterator) {
    this.iterators.add(iterator);
  }

  @Override
  public boolean hasNext() {
    if (this.current >= this.iterators.size())
      return false;

    Iterator currentIterator = this.iterators.get(this.current);

    while (true) {
      if (currentIterator.hasNext()) {
        return true;
      } else {
        this.current++;
        if (this.current >= iterators.size())
          break;
        currentIterator = iterators.get(this.current);
      }
    }
    return false;
  }

  @Override
  public void remove() {
    this.iterators.get(this.current).remove();
  }

  @Override
  public T next() {
    if (this.iterators.isEmpty()) throw new NoSuchElementException();

    Iterator currentIterator = iterators.get(this.current);
    while (true) {
      if (currentIterator.hasNext()) {
        return currentIterator.next();
      } else {
        this.current++;
        if (this.current >= iterators.size())
          break;
        currentIterator = iterators.get(current);
      }
    }
    throw new NoSuchElementException();
  }

  public void clear() {
    this.iterators.clear();
    this.current = 0;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy