ChainedIterator.java
/***************************************************************************
Copyright 2008 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** This class implements an iterator that "flattens" a set of iterators.
Given an iterator(or array of iterators), this class implements .hasNext() and .next() methods
to provide the illusion of one iterator over the entire set.
@param <E> The type of elements this iterator produces.
*/
public final class ChainedIterator<E> implements Iterator<E> {
private final Iterator<Iterator<E>> chain;
/** Create a flat iterator from a list of iterators.
@param list The list of iterators.
*/
public ChainedIterator(final Iterable<Iterator<E>> list) { this.chain = list.iterator(); }
private boolean queuedNext = false;
private E next = null;
private Iterator<E> cur = null;
@Override public boolean hasNext() {
if(queuedNext) { return true; }
try {
next = findFirst();
} catch (final NoSuchElementException nsee) {
return false;
}
queuedNext = true;
return true;
}
@Override public E next() {
if(queuedNext) {
queuedNext = false;
return next;
}
return findFirst();
}
@Override public void remove() { throw new UnsupportedOperationException(); }
private E findFirst() {
if((cur!=null) && (cur.hasNext())) { return cur.next(); }
while(chain.hasNext()) {
cur = chain.next();
if(cur.hasNext()) { return cur.next(); }
}
throw new NoSuchElementException();
}
}