java.util.Optional.map(Function)
The method Optional.map(Function) 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 java.util.Optional.map(Function) method is as follows:
public <U> Optional<U> map(Function<? super T,? extends U> mapper)
The method is available since Java 8.
Parameters
- 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.
Exceptions
- NullPointerException: when the mapping function is null
Example usage
In the following code we use java.util.Optional.map(Function):
package com.farenda.java.util; import java.util.Optional; public class OptionalExamples { public static void main(String[] args) { String value = Optional.of("small") .map(String::toUpperCase) .get(); 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) .map(String::toUpperCase) .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