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

The flatMap method is a special method in the Optional class in Java, if a method returns an Optional, you can use flatMap to avoid nested Optional<Optional<T>> situations.

Here is an example:

package org.kodejava.util;

import java.util.Optional;

public class OptionalFlatMap {
    public static void main(String[] args) {
        Optional<String> nonEmptyGender = Optional.of("male");
        Optional<String> emptyGender = Optional.empty();

        System.out.println("Non-Empty Optional:: " + nonEmptyGender.flatMap(OptionalFlatMap::getGender));
        System.out.println("Empty Optional:: " + emptyGender.flatMap(OptionalFlatMap::getGender));
    }

    static Optional<String> getGender(String gender) {
        if (gender.equals("male")) {
            return Optional.of("Gender is male");
        } else if (gender.equals("female")) {
            return Optional.of("Gender is female");
        } else {
            return Optional.empty();
        }
    }
}

In this example, two Optional<String> objects are created: one with a value (nonEmptyGender) and one without a value (emptyGender).

The flatMap method is used to apply the method getGender to the value of each Optional<String> (if it exists). Since getGender returns an Optional<String>, using flatMap avoids creating Optional<Optional<String>> objects, and instead directly returns an Optional<String>, that we can easily consume.

The getGender method returns an Optional object, that describes the gender if it is “male” or “female”, or an empty Optional if the gender is neither “male” nor “female”.

The result of calling flatMap will hence be an Optional<String> describing the gender if the gender is “male” or “female”, or an empty Optional in all other cases. This applies to both the non-empty and the empty Optional<String> in the example.

The final output will be:

Non-Empty Optional:: Optional[Gender is male]
Empty Optional:: Optional.empty

In both cases, note that flatMap directly returns the result of getGender, which itself is an Optional. This is different from if map was used, which would have resulted in a nested Optional.

Wayan

Leave a Reply

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