package collections;

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

import common.Predicate;

public class FilteringIterator<T> implements Iterator<T> {

	private final Iterator<T> iterator;
	private final Predicate<T> predicate;
	private T nextItem;

	public FilteringIterator(Iterator<T> iterator, Predicate<T> predicate) {
		this.iterator = iterator;
		this.predicate = predicate;
		nextItem = null;
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		while (iterator.hasNext()) {
			T item = iterator.next();
			if (predicate.apply(item)) {
				nextItem = item;
				break;
			}
		}

		return nextItem != null;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		iterator.remove();
		if (nextItem != null) {
			nextItem = null;
		}
	}
}

@@ -266,16 +266,40 @@
 extItem;
+%0A%09private boolean dirty;
 %0A%0A%09publi
@@ -435,32 +435,54 @@
 extItem = null;%0A
+%09%09this.dirty = false;%0A
 %09%7D%0A%0A%09@Override%0A%09
@@ -858,16 +858,32 @@
 = null;%0A
+%09%09dirty = true;%0A
 %09%09return
@@ -893,16 +893,16 @@
 Return;%0A
-
 %09%7D%0A%0A%09@Ov
@@ -939,75 +939,84 @@
 %0A%09%09i
-terator.remove();%0A%09%09if (nextItem != null) %7B%0A%09%09%09nextItem = null;%0A%09%09%7D
+f (!dirty) %7B%0A%09%09%09throw new IllegalStateException();%0A%09%09%7D%0A%0A%09%09iterator.remove();
 %0A%09%7D%0A

Fix for filtering iterator.