How do I use filter() method of Optional object?

The java.util.Optional class in Java provides a filter method. It’s used to apply a condition on the value held by this Optional.

Here is an example of how to use Optional‘s filter method:

package org.kodejava.util;

import java.util.Optional;

public class OptionalFilter {
    public static void main(String[] args) {

        // Creating Optional object and assigning a value
        Optional<String> myOptional = Optional.of("Hello");

        // Applying filter method on Optional
        Optional<String> result = myOptional.filter(value -> value.length() > 5);

        // Print the result
        // This will not print anything because the length of "Hello" 
        // is not greater than 5.
        result.ifPresent(System.out::println);
    }
}

In this example, the filter method is used to apply a condition on the value held by this myOptional object. The condition is that the length of the value should be greater than 5. If the value satisfies the condition, it is returned. Otherwise, an empty Optional object is returned.

The ifPresent method is used to print the value held by this Optional, if it is non-empty. This particular use of filter will not print anything because the string “Hello” length is not greater than 5.

You can use isEmpty method to check whether Optional is empty.

if (result.isEmpty()) {
   System.out.println("The Optional is empty");
}

In this case, it would print “The Optional is empty”.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.