package company.iterators;
import company.IPredicate;
import employee.IEmployee;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Created by Wojciech Milewski.
*/
public class PredicateIterator extends DFSIterator<IEmployee>{
private final IPredicate predicate;
public PredicateIterator(Iterator<IEmployee> iterator, IPredicate predicate) {
super(iterator);
this.predicate = predicate;
}
@Override
public IEmployee next() {
final Stack<Iterator<IEmployee>> stack = super.getStack();
IEmployee next;
do {
if (!hasNext()) {
throw new NoSuchElementException("There is no next element");
}
next = stack.peek().next();
}
while (!predicate.apply(next));
if (next instanceof Iterable) {
stack.push(((Iterable) next).iterator());
}
return next;
}
}