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 Optional class is present in the java.util package.

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 predicate functionFunction checks if your input meets some condition to be executed.

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 Optional class.
import java.util.Optional;
  • In line 5, we created an Optional object of the Integer type with value 1 using of method.
Optional<Integer> optional1 = Optional.of(1);
  • In line 7, we called the filter method on the optional1 object. For the filter method, a predicate function that checks if the value is greater than 0 is passed as an argument. This method returns an Optional object with value 1 because the optional1 object 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 empty method to get an empty Optional object of the Integer type. The returned object doesn’t have any value.
Optional<Integer> optional2 = Optional.empty();
  • In line 12, we called the filter method on the optional2 object. For the filter method, a predicate function that checks if the value is greater than 0 is passed as an argument. This method returns an empty Optional object because the optional2 object doesn’t contain any values.
result =  optional2.filter((val)-> val > 0);
result; // Optional.empty

Free Resources