CKTIS / Java
Stream.filter: practical reference
Stream.filter: practical reference: Stream.filter(predicate) is a stateless intermediate operation that passes only elements for which the predicate returns true.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.filter(...)Stream.filter(predicate) is a stateless intermediate operation that passes only elements for which the predicate returns true.
Place it early in a pipeline to reduce data for later map, distinct, collect, or reduction while preserving source encounter order.
It is lazy: the predicate runs only when a terminal operation starts and may not see every element because of short-circuiting or optimization.
The predicate must be non-interfering and stateless and cannot be null; if the source contains null, the predicate itself must handle it.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).toList();
System.out.println(result);
}
}
Result
[2, 4]
The example exercises the documented element in a small deterministic program and compares exact standard output.