CKTIS / Java
Optional.filter: practical reference
Optional.filter: practical reference: Optional.filter(predicate) returns an Optional describing a present value that satisfies the predicate, empty when it does not, and stays empty for an empty receiver.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Optional.filter(...)Optional.filter(predicate) returns an Optional describing a present value that satisfies the predicate, empty when it does not, and stays empty for an empty receiver.
Use filter to retain an optional value only when it meets a domain condition, without manually branching on isPresent.
The predicate is not run for an empty receiver, so do not place required side effects in it; an exception from it propagates to the caller.
A null predicate argument causes NullPointerException; a present value that passes is neither copied nor transformed.
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 value = java.util.Optional.of("Java").filter(text -> text.length() > 3);
System.out.println(value.orElse("missing"));
}
}
Result
Java
The example exercises the documented element in a small deterministic program and compares exact standard output.