The filter() method of the Optional class checks the value against a specified Predicate and returns an Optional based on the result. If the Optional is empty or the predicate does not match, it returns an empty Optional.
- The Predicate defines the condition used to filter the value.
- When the condition returns true, the existing value remains in the Optional.
- A NullPointerException is thrown when the specified predicate is null.
Example: Program uses filter() to check whether the value stored in an Optional is even and retains it only when the condition is satisfied.
import java.util.Optional;
public class GFG {
public static void main(String[] args) {
Optional<Integer> number = Optional.of(9456);
Optional<Integer> result =
number.filter(n -> n % 2 == 0);
System.out.println(result);
}
}
Output
Optional[9456]
Explanation: The filter() method checks whether 9456 is even using the predicate n -> n % 2 == 0. Since the condition is true, the value remains inside the Optional.
Syntax
public Optional<T> filter(Predicate<? super T> predicate)
- Parameter: predicate specifies the condition used to filter the value.
- Return Value: The method returns the existing Optional when the predicate matches. Otherwise, it returns an empty Optional.
- Exception: NullPointerException is thrown when the specified predicate is null.
Ways to Use filter() with Optional
The filter() method works with both present and empty Optional values, applying a Predicate to retain a value only when the specified condition is satisfied.
1. Using filter() with a Present Value
The following program creates an Optional containing 9456 and checks whether the value is even. Since 9456 satisfies the predicate, the value remains in the Optional.
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<Integer> op = Optional.of(9456);
System.out.println("Optional: " + op);
System.out.println("Filtered value for odd or even: "
+ op.filter(num -> num % 2 == 0));
}
}
Output
Optional: Optional[9456] Filtered value for odd or even: Optional[9456]
Explanation: The predicate checks whether 9456 is divisible by 2. The condition is true, so filter() returns the Optional containing 9456.
2. Using filter() with an Empty Optional
The following program applies filter() to an empty Optional. Since no value is present, the predicate does not execute.
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<Integer> op = Optional.empty();
System.out.println("Optional: " + op);
System.out.println("Filtered value for odd or even: "
+ op.filter(num -> num % 2 == 0));
}
}
Output
Optional: Optional.empty Filtered value for odd or even: Optional.empty
Explanation: The Optional contains no value, so filter() returns Optional.empty(). The predicate is not evaluated because there is no value to filter.