Optional: map, flatMap and orElseThrow chain safely

Optional shines when chaining lookups that may fail. Reserve it for return values - it is a poor choice for fields and parameters.

Code
record Address(String city) {}
record User(String name, Optional<Address> address) {}

var withCity = new User("Ava", Optional.of(new Address("Chennai")));
var without = new User("Ben", Optional.empty());

for (User u : List.of(withCity, without)) {
    String city = u.address().map(Address::city).map(String::toUpperCase).orElse("UNKNOWN");
    System.out.println(u.name() + " -> " + city);
}

try {
    without.address().orElseThrow(() -> new NoSuchElementException("no address for Ben"));
} catch (NoSuchElementException e) {
    System.out.println("orElseThrow: " + e.getMessage());
}
Output
Ava -> CHENNAI
Ben -> UNKNOWN
orElseThrow: no address for Ben
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30