Skip to content

Instantly share code, notes, and snippets.

@ylegall
Last active February 24, 2017 09:54
Show Gist options
  • Save ylegall/6331216 to your computer and use it in GitHub Desktop.
Save ylegall/6331216 to your computer and use it in GitHub Desktop.
Iterator of iterators
import java.util.Iterator;
public class Iterators<T> implements Iterator<T> {
private Iterator<T> current;
private Iterator<Iterator<T>> cursor;
public Iterators(Iterable<Iterator<T>> iterators) {
if (iterators == null) throw new IllegalArgumentException("iterators is null");
this.cursor = iterators.iterator();
}
private Iterator<T> findNext() {
while (cursor.hasNext()) {
current = cursor.next();
if (current.hasNext()) return current;
}
return null;
}
@Override
public boolean hasNext() {
if (current == null || !current.hasNext()) {
current = findNext();
}
return (current != null && current.hasNext());
}
@Override
public T next() {
return current.next();
}
@Override
public void remove() {
if (current != null) {
current.remove();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment