Skip to content
Tutorials Center
My learning

Topics

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.

Java
List<Integer> even = numbers.stream()
    .filter(n -> n % 2 == 0)
    .toList();

Try it

Java Filtering numbers and strings

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.

Java Filtering objects and counting

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

Java
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, so count() must actually traverse the elements.
  • Null elements: the predicate receives null as is, so s -> s.isEmpty() throws NullPointerException on a null element. Filter with Objects::nonNull first.
  • Chaining: several filter calls 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) or p.negate() keeps the elements that do not match, e.g. filter(Predicate.not(String::isBlank)).
  • Not a remover: filter never changes the source. To remove from a mutable collection use removeIf.
  • Use takeWhile when the data is sorted and you want to stop at the first failure.