Java 25 (LTS) reference · Optional

Java Optional map() Method

Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

optional.map(mapper)

Parameters

ParameterDescription
mapper
Function<T, U>
Function applied to the value.

Return value

An Optional<U>.

Examples

Transform safely
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Optional<String> email = Optional.of("[email protected]");
        System.out.println(email.map(String::toLowerCase).map(e -> e.split("@")[1]).orElse("?"));
        System.out.println(Optional.<String>empty().map(String::length).orElse(0));
    }
}

Output

example.com
0

Run this on your computer — see “Get Started” for setup.

Navigate nullable fields
import java.util.*;

public class Main {
    public static void main(String[] args) {
        record Address(String city) {}
        record User(String name, Address address) {}
        User ben = new User("Ben", null);
        String city = Optional.ofNullable(ben.address()).map(Address::city).orElse("unknown city");
        System.out.println(city);
    }
}

Output

unknown city

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?