Java Optional map() Method
Example
Change a name to uppercase, if there is a name:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();
System.out.println(name.map(n -> n.toUpperCase()).orElse("Guest"));
System.out.println(noName.map(n -> n.toUpperCase()).orElse("Guest"));
}
}
Definition and Usage
The map() method changes the value with a lambda expression (a short block of code that works like a method), and returns the result in a new Optional.
If the Optional is empty, the lambda is not run and the result is an empty Optional. If the lambda returns null, the result is also empty.
Tip: If the lambda returns an Optional, use flatMap() instead.
Syntax
public <U> Optional<U> map(Function<? super T, ? extends U> mapper)
T refers to the data type of the value in the Optional. U refers to the data type of the new value.
Parameter Values
| Parameter | Description |
|---|---|
| mapper | Required. A Function object or lambda expression that takes the value and returns a new value. |
Technical Details
| Returns: | An Optional with the new value, or an empty Optional if there is no value. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods