Iterator that filters elements from another iterator


import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Abstract Iterator that filters values from a wrapped Iterator
 * 
 * @author Karsten Lehmann
 */
public abstract class FilterIterator <T> implements Iterator<T> {
	/** wrapped iterator */
	private Iterator<T> m_wrappedIt;
	/** next element */
	private T m_nextEl;
	/** flag to enforce fetchNext() in first hasNext()/next() call */
	private boolean firstCallDone;

	/**
	 * Creates a new iterator
	 * 
	 * @param wrappedIt wrapped iterator
	 */
	public FilterIterator(Iterator<T> wrappedIt) {
		m_wrappedIt = wrappedIt;
	}

	/**
	 * Implement this method to filter out values
	 * 
	 * @param o object from wrapped iterator
	 * @return <code>true</code>, if object is accepted
	 */
	public abstract boolean isAccepted(T o);

	/**
	 * Reads the next accepted element
	 */
	private void fetchNext() {
		while (m_wrappedIt.hasNext()) {
			m_nextEl=m_wrappedIt.next();
			if (isAccepted(m_nextEl))
				return;
		}
		m_nextEl=null;
	}

	public void remove() {
		throw new UnsupportedOperationException("This method is not supported.");
	}

	public boolean hasNext() {
		if (!firstCallDone)  {
			fetchNext();
			firstCallDone=true;
		}

		if (m_nextEl!=null)
			return true;
		return false;
	}

	public T next() {
		if (!firstCallDone)  {
			fetchNext();
			firstCallDone=true;
		}

		if (m_nextEl==null)
			throw new NoSuchElementException("No more elements available.");

		T val=m_nextEl;
		fetchNext();
		return val;
	}

}
All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
No comments yetLogin first to comment...