Java Reference ยท Streams and Functional
Java Stream.filter() method
Reference for Java Stream.filter(): keep only the elements that match a Predicate, combine conditions, and avoid common mistakes with null and side effects.
filter() is an intermediate operation that keeps the elements for which a Predicate returns true and drops the rest. The result is a new stream with the same element type; the source is untouched.
Like all intermediate operations it is lazy: the predicate runs only when a terminal operation pulls elements through the pipeline, and it runs once per element that reaches this stage.
List<Integer> even = numbers.stream() .filter(n -> n % 2 == 0) .toList();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Stream<T> filter(Predicate<? super T> predicate) IntStream filter(IntPredicate predicate) // also on LongStream, DoubleStream
| Name | Description |
|---|---|
predicate |
A non-interfering, stateless test. Elements for which it returns true stay in the stream. |
Returns: a stream of the matching elements, in the original encounter order.
Throws: NullPointerException if predicate is null.
Usage notes
- Order and size: survivors keep their relative order. The stream is no longer
SIZED, socount()must actually traverse the elements. - Null elements: the predicate receives
nullas is, sos -> s.isEmpty()throwsNullPointerExceptionon a null element. Filter withObjects::nonNullfirst. - Chaining: several
filtercalls are equivalent to one with&&and read well; put the cheapest or most selective test first. - Keep predicates pure. Do not mutate outside state in a predicate; with parallel streams the result becomes unpredictable.
- Opposite of filter:
Predicate.not(p)(Java 11) orp.negate()keeps the elements that do not match, e.g.filter(Predicate.not(String::isBlank)). - Not a remover:
filternever changes the source. To remove from a mutable collection useremoveIf. - Use
takeWhilewhen the data is sorted and you want to stop at the first failure.
Related
map(),takeWhile(),anyMatch(),Predicate- Lessons: Streams, Functional interfaces