Class FilterIterator<A,B>

java.lang.Object
net.cscott.jutil.FilterIterator<A,B>
All Implemented Interfaces:
Iterator<B>

public class FilterIterator<A,B> extends Object implements Iterator<B>
A FilterIterator filters and maps a source Iterator to generate a new one: it returns map.apply(o) for each element o of the source for which filter.test(o) is true.
 Iterator<String> names = FilterIterator.map(people, Person::name);
 Iterator<Person> adults = FilterIterator.filter(people, p -> p.age() >= 18);
 
A Stream does the same, with stream.filter(filter).map(map).iterator().

Note that this implementation reads one element ahead, so if the filter changes for an object 'o' between the time that is read (when next() is called, returning the object preceding 'o', and checking that 'o' satisfies the current filter) and the time when hasNext() is called, 'o' will still be returned, regardless of what the filter now says about it. Thus, it is recommended that only filters which remain consistent throughout the iteration be used.

Author:
C. Scott Ananian <cananian@alumni.princeton.edu>