Java Programming Tutorials

Java programming tutorials with many code examples!

Java Util Optional map(Function)

The method applies the given function to the optional value if it is present and returns an optional with the result or empty optional.

Method signature

The signature of the method is as follows:

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

The method is available since Java 8.


  • Function<? super T,? extends U> mapper: a mapping function to apply to the value if present

Return value

Optional with the value returned from the mapping function or empty optional.


  • NullPointerException: when the mapping function is null

Example usage

In the following code we use


import java.util.Optional;

public class OptionalExamples {

    public static void main(String[] args) {
        String value = Optional.of("small")
        System.out.println("of 'small': " + value);

        value = Optional.of("null from function")
                .map(s -> (String) null)
                .orElse("no value");
        System.out.println("Null from mapper: " + value);

        value = Optional.<String>ofNullable(null)
                .orElse("no value");
        System.out.println("Of nullable: " + value);

The above code produces the following output:

of 'small': SMALL
Null from mapper: no value
Of nullable: no value
Was it helpful? Share!