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 thejava.util
package.
Read more about Optional class here.
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.
public Optional<T> filter(Predicate<? super T> predicate)
The argument is the
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.
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);}}
In the code above:
Optional
class.import java.util.Optional;
Optional
object of the Integer
type with value 1
using of
method.Optional<Integer> optional1 = Optional.of(1);
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]
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();
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