Last active
February 24, 2017 09:54
-
-
Save ylegall/6331216 to your computer and use it in GitHub Desktop.
Iterator of iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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