Sub topic 9
Chaining Lookups with flatMap
Real programs often need several lookups in a row. You find a customer, then the customer's address, then the city. Any of those steps might find nothing. This chapter shows how flatMap joins such steps into one clear chain.
The Problem: Optional Inside Optional
You already know map. It takes the value inside an Optional, changes it, and wraps the result in a new Optional.
Suppose a method returns an Optional itself. A method like that is an Optional-returning method: its return type is Optional<Something>, because it might not find a result. If you pass that method to map, map wraps the result again. You end up with an Optional inside an Optional.
import java.util.Optional;
public class NestedDemo {
record Address(String city) {}
record Customer(String name, Address address) {}
static Optional<Address> addressOf(Customer c) {
return Optional.ofNullable(c.address());
}
public static void main(String[] args) {
Optional<Customer> customer =
Optional.of(new Customer("Lin", new Address("Oslo")));
Optional<Optional<Address>> nested = customer.map(NestedDemo::addressOf);
Optional<Address> flat = customer.flatMap(NestedDemo::addressOf);
System.out.println(nested); // Optional[Optional[Address[city=Oslo]]]
System.out.println(flat); // Optional[Address[city=Oslo]]
}
}The type Optional<Optional<Address>> is awkward. You would have to unwrap it twice. flatMap avoids this. It calls your method and returns that method's Optional directly, without adding another layer.
How flatMap Works
flatMap follows two rules:
- If the Optional is empty,
flatMapskips your method and returns an empty Optional. - If a value is present,
flatMapcalls your method with it and returns whatever Optional the method gives back.
Here is a picture of a chain of lookups. Each step can end the chain early.
A Worked Example
This program has three cases: a customer with an address, a customer with no address, and a customer who does not exist.
import java.util.Map;
import java.util.Optional;
public class FlatMapDemo {
record Address(String city) {}
record Customer(String name, Address address) {}
static final Map<String, Customer> CUSTOMERS = Map.of(
"c1", new Customer("Lin", new Address("Oslo")),
"c2", new Customer("Sam", null));
static Optional<Customer> findCustomer(String id) {
return Optional.ofNullable(CUSTOMERS.get(id));
}
static Optional<Address> addressOf(Customer c) {
return Optional.ofNullable(c.address());
}
static String cityFor(String id) {
return findCustomer(id)
.flatMap(FlatMapDemo::addressOf)
.map(Address::city)
.orElse("No city");
}
public static void main(String[] args) {
System.out.println(cityFor("c1")); // Oslo
System.out.println(cityFor("c2")); // No city (no address)
System.out.println(cityFor("c3")); // No city (no customer)
}
}Read cityFor from top to bottom:
findCustomer(id)gives anOptional<Customer>.flatMap(FlatMapDemo::addressOf)gives anOptional<Address>. You useflatMapbecauseaddressOfreturns an Optional.map(Address::city)gives anOptional<String>. You usemapbecausecity()returns a plainString.orElse("No city")gives the final answer.
The chain contains no if checks and no null checks.
map or flatMap?
Look at what your method returns.
| Your method returns | Use | Result type |
|---|---|---|
| A plain value, like `String` | `map` | `Optional<String>` |
| An Optional, like `Optional<Address>` | `flatMap` | `Optional<Address>` |
Exercises
Exercise
A method Optional<String> emailOf(User u) looks up a user's email. You have Optional<User> user. Should you write user.map(this::emailOf) or user.flatMap(this::emailOf) to get an Optional<String>, and why?
Show answer
Use user.flatMap(this::emailOf). emailOf already returns an Optional, so map would produce Optional<Optional<String>>. flatMap returns the method's Optional directly, which gives Optional<String>.
Exercise
In the worked example, what does cityFor("c2") print, and at which step does the chain become empty?
Show answer
It prints "No city". findCustomer("c2") finds Sam, but Sam's address is null, so addressOf returns Optional.empty(). The chain becomes empty at the flatMap step, map is skipped, and orElse supplies "No city".