Package net.cscott.jutil
Class FilterIterator<A,B>
java.lang.Object
net.cscott.jutil.FilterIterator<A,B>
- All Implemented Interfaces:
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>
-
Nested Class Summary
Nested Classes -
Constructor Summary
ConstructorsConstructorDescriptionFilterIterator(Iterator<? extends A> i, Predicate<? super A> filter, Function<? super A, ? extends B> map) Creates aFilterIteratorwhich returnsmap.apply(o)for each elementoofifor whichfilter.test(o)is true.FilterIterator(Iterator<A> i, FilterIterator.Filter<A, B> f) Deprecated.UseFilterIterator(Iterator,Predicate,Function), orfilter(Iterator,Predicate)ormap(Iterator,Function), with lambdas instead of aFilterIterator.Filter. -
Method Summary
Modifier and TypeMethodDescriptionstatic <A> FilterIterator<A, A> booleanhasNext()static <A,B> FilterIterator <A, B> next()Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface java.util.Iterator
forEachRemaining, remove
-
Constructor Details
-
FilterIterator
public FilterIterator(Iterator<? extends A> i, Predicate<? super A> filter, Function<? super A, ? extends B> map) Creates aFilterIteratorwhich returnsmap.apply(o)for each elementoofifor whichfilter.test(o)is true.- Since:
- 2.0
-
FilterIterator
Deprecated.UseFilterIterator(Iterator,Predicate,Function), orfilter(Iterator,Predicate)ormap(Iterator,Function), with lambdas instead of aFilterIterator.Filter.Creates aFilterIterator.
-
-
Method Details
Predicateand aFunction, which can be lambdas, withFilterIterator(Iterator,Predicate,Function),filter(Iterator,Predicate)ormap(Iterator,Function).