What is the Optional.filter method in Java?
In Java, the Optional object is a container object that may or may not contain a value. Using its isPresent method, we can replace the multiple null check.
The
Optionalclass is present in thejava.utilpackage.
Read more about Optional class here.
What is the filter method of the Optional class?
The filter method will check if the Optional object contains a value and matches the passed predicate function. If it matches the conditions above then an Optional object with the value is returned. Otherwise, an empty Optional object is returned.
Syntax
public Optional<T> filter(Predicate<? super T> predicate)
Argument
The argument is the
Return value
If the Optional object contains a value and satisfies the predicate function then the Optional object with value is returned. Otherwise, an empty Optional object is returned.
Code
The code below shows how to use the filter method.
import java.util.Optional;class OptionalFilterExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);Optional<Integer> result = optional1.filter((val)-> val > 0);System.out.println("Returned value from filter method is : " + result);Optional<Integer> optional2 = Optional.empty();System.out.println("\nOptional2 : " + optional2);result = optional2.filter((val)-> val > 0);System.out.println("Returned value from filter method is : " + result);}}
Explanation
In the code above:
- In line 1, we imported the
Optionalclass.
import java.util.Optional;
- In line 5, we created an
Optionalobject of theIntegertype with value1usingofmethod.
Optional<Integer> optional1 = Optional.of(1);
- In line 7, we called the
filtermethod on theoptional1object. For thefiltermethod, a predicate function that checks if the value is greater than0is passed as an argument. This method returns anOptionalobject with value1because theoptional1object contains the value and satisfies the passed Predicated function.
Optional<Integer> result = optional1.filter((val)-> val > 0);
result; // Optional[1]
- In line 10, we used the
emptymethod to get an emptyOptionalobject of theIntegertype. The returned object doesn’t have any value.
Optional<Integer> optional2 = Optional.empty();
- In line 12, we called the
filtermethod on theoptional2object. For thefiltermethod, a predicate function that checks if the value is greater than0is passed as an argument. This method returns an emptyOptionalobject because theoptional2object doesn’t contain any values.
result = optional2.filter((val)-> val > 0);
result; // Optional.empty