Java Optional filter() Method
Example
Keep the name only if it starts with a certain letter:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
System.out.println(name.filter(n -> n.startsWith("L")).orElse("No match"));
System.out.println(name.filter(n -> n.startsWith("J")).orElse("No match"));
}
}
Definition and Usage
The filter() method tests the value with a condition. If the value matches, it returns the same Optional. If not, it returns an empty Optional.
The condition is a lambda expression (a short block of code that works like a method) that returns true or false. If the Optional is already empty, the condition is not used and the result is empty.
Syntax
public Optional<T> filter(Predicate<? super T> predicate)
T refers to the data type of the value in the Optional.
Parameter Values
| Parameter | Description |
|---|---|
| predicate | Required. A Predicate object or lambda expression that tests the value and returns true or false. |
Technical Details
| Returns: | The same Optional if the value matches the condition, otherwise an empty Optional. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods