Skip to content

Instantly share code, notes, and snippets.

@arriolac
Last active January 6, 2016 20:01
Show Gist options
  • Save arriolac/dd68f1f56361930821f4 to your computer and use it in GitHub Desktop.
Save arriolac/dd68f1f56361930821f4 to your computer and use it in GitHub Desktop.
An Iterator that flattens iterating over a list of Iterators.
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* An Iterator that flattens iterating over a list of Iterators.
*
* Created by chris on 1/5/16.
*/
public class FlatIterator<Type> implements Iterator<Type> {
private Iterator<Type> currentIterator;
private Iterator<Iterator<Type>> iterator;
private Type next;
public FlatIterator(List<Iterator<Type>> iterators) {
iterator = iterators.iterator();
next = null;
if (iterator.hasNext()) {
currentIterator = iterator.next();
}
}
@Override public boolean hasNext() {
return next != null || setNext();
}
@Override public Type next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
final Type type = next;
next = null;
return type;
}
@Override public void remove() {
iterator.remove();
}
private boolean setNext() {
if (next != null) {
return true;
} else {
while (true) {
if (currentIterator.hasNext()) {
next = currentIterator.next();
return true;
} else {
if (iterator.hasNext()) {
currentIterator = iterator.next();
} else {
return false;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment