Java SE API
Optional.filter()
Keep a present value only when the predicate accepts it. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
Optional<T> filter(Predicate<? super T> predicate)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| predicate | Predicate<? super T> | Non-null inclusion test |
Return Value
Optional<T>
Keep a present value only when the predicate accepts it.
Working Example
Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var result = Optional.of(" Bolt ").map(String::strip).filter(s -> !s.isEmpty()); System.out.println(result.orElseThrow()); System.out.println(Optional.of(" ").map(String::strip).filter(s -> !s.isEmpty()).isEmpty()); System.out.println(Optional.of("bolt").map(s -> (String)null).isEmpty()); }}