Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.map()

Transforms the value inside an `Optional` if there is one.

Available since: Java 8

Syntax

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

Parameters

ParameterTypeDescription
mapperFunction<? super T, ? extends U>The transformation of the value.

Return value

Optional<U>An `Optional` with the result, or an empty one.

Examples

A chain without null checks:

record Address(String city) {}
record User(String name, Address address) {}
 
void main() {
    Optional<User> user = Optional.of(new User("Anna", new Address("Paris")));
    String city = user.map(User::address).map(Address::city).orElse("unknown");
    IO.println(city);
    Optional<User> nobody = Optional.empty();
    IO.println(nobody.map(User::name).map(String::length).orElse(0));
}

Output:

Paris
0

Notes

On an empty Optional the function is not called and the result stays empty. If the function returns null, the result becomes empty too. If the function itself returns an Optional, use flatMap(); for a condition use filter().

See also

  • Optional.orElse() — Returns the value, or a fallback if there is none.
  • Stream.map() — Transforms every element of a stream.
  • Function — A function that takes a value of type `T` and returns a value of type `R`.

In the tutorial

  • Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.

Thanks for reading!

Donate to the site — we work hard for you.