Java

Optional Chains — flatMap, filter

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`flatMap` lets you chain Optional-returning methods without nested `if`. `filter` short-circuits to empty if the predicate fails. The functional equivalent of safe-navigation `?.`.
Java
Raw
import java.util.*;

class Demo {
    record Address(String city, String zip) {}
    record User(String name, Optional<Address> address) {}

    Optional<User> findUser(int id) {
        return Optional.of(new User("Alice", Optional.of(new Address("Austin", "78704"))));
    }

    void example() {
        // Chain through nested optionals
        Optional<String> city = findUser(1)
            .flatMap(User::address)              // Optional<Address>
            .map(Address::city);                 // Optional<String>
        System.out.println(city.orElse("none"));

        // Filter conditionally — empty if predicate fails
        Optional<String> longCity = findUser(1)
            .flatMap(User::address)
            .map(Address::city)
            .filter(c -> c.length() > 10);
        System.out.println(longCity);            // Optional.empty if city <= 10 chars

        // Combined with orElseThrow for must-exist semantics
        String requiredZip = findUser(1)
            .flatMap(User::address)
            .map(Address::zip)
            .orElseThrow(() -> new IllegalStateException("no zip"));
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.