Design an iterator for a collection of collections in java. The iterator should hide the nesting, allowing you to iterate all of the elements belonging to all of the collect
Here is another implementation:
import java.util.Iterator;
import java.util.NoSuchElementException;
import static java.util.Collections.emptyIterator;
public class Multiterator implements Iterator {
private Iterator> root;
private Iterator current;
public Multiterator(Iterator> root) {
this.root = root;
current = null;
}
@Override
public boolean hasNext() {
if (current == null || !current.hasNext()) {
current = getNextNonNullOrEmpty(root);
}
return current.hasNext();
}
private Iterator getNextNonNullOrEmpty(Iterator> root) {
while (root.hasNext()) {
Iterator next = root.next();
if (next != null && next.hasNext()) {
return next;
}
}
return emptyIterator();
}
@Override
public E next() {
if (current == null) {
throw new NoSuchElementException();
}
return current.next();
}
}