Sub topic 9
Chaining Lookups with flatMap
In earlier chapters you used map to change the value inside an Optional. That works well when your function returns a plain value, such as a String or an int. Sometimes, though, the function you want to call already returns an Optional. Then map gives you an awkward result: an Optional inside another Optional.
This chapter shows why that happens and how flatMap fixes it. You will also see how to chain several lookups in a row, where any step might find nothing.
The Problem: One Lookup Leads to Another
Real programs often look things up in steps. Here is a common example:
- Find a customer by their ID. The customer might not exist.
- Get that customer's address. The customer might not have one.
- Read the city from the address.
Each step depends on the one before it. If any step finds nothing, the whole answer is "no city."
The old way with null checks
Before Optional, you would write a chain of if checks. A null check is an if statement that tests whether a variable is null before you use it.
import java.util.Map;
public class NullCheckDemo {
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")));
public static void main(String[] args) {
String city = "No city";
Customer customer = CUSTOMERS.get("c1");
if (customer != null) {
Address address = customer.address();
if (address != null) {
if (address.city() != null) {
city = address.city();
}
}
}
System.out.println(city); // Oslo
}
}This code works, but each new step adds another level of nesting. If you forget one check, you get a NullPointerException. A record is a short way to write a class that just holds data. Records need Java 16 or later.
Why map Is Not Enough
Suppose you write your lookup methods to return Optional. That is good practice, because the return type tells callers that the value might be missing.
static Optional<Customer> findCustomer(String id) { ... }
static Optional<Address> addressOf(Customer c) { ... }Now try to connect them with map. The map method takes the value inside the Optional, runs your function on it, and wraps the result in a new Optional. Since addressOf already returns an Optional<Address>, map wraps that Optional again.
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);
System.out.println(nested); // Optional[Optional[Address[city=Oslo]]]
Optional<Address> flat = customer.flatMap(NestedDemo::addressOf);
System.out.println(flat); // Optional[Address[city=Oslo]]
}
}Look at the type Optional<Optional<Address>>. It is a box inside a box. To reach the address you would have to open two boxes, which is clumsy and easy to get wrong.
The flatMap call gives you Optional<Address>, one box with the address inside. "Flat" means it removes the extra layer.
How flatMap Works
The flatMap method takes a function. That function receives the value inside the Optional and must return an Optional of its own.
Here is what flatMap does, step by step:
- If the Optional is empty,
flatMapdoes not call your function. It returns an empty Optional. - If the Optional has a value,
flatMapcalls your function with that value. - It returns the Optional your function gave back, without wrapping it again.
The table below compares the two methods.
| Method | Your function returns | Result type | Wraps the result? |
|---|---|---|---|
| `map` | A plain value, like `Address` | `Optional<Address>` | Yes |
| `flatMap` | An Optional, like `Optional<Address>` | `Optional<Address>` | No |
This gives you a simple rule to remember:
- If your function returns a plain value, use
map. - If your function returns an Optional, use
flatMap.
A Full Lookup Chain
Now let us rewrite the null-check example with Optional. This version adds a second customer, Sam, who has no address. It also asks for an ID that does not exist.
import java.util.Map;
import java.util.Optional;
public class FlatMapChainDemo {
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(FlatMapChainDemo::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
System.out.println(cityFor("c9")); // No city
}
}Let us trace each call.
- For
"c1",findCustomerfinds Lin.flatMapcallsaddressOf, which returns an Optional holding Oslo's address.mapreads the city.orElseis not needed, so the result is"Oslo". - For
"c2",findCustomerfinds Sam.addressOfreturns an empty Optional because Sam's address isnull. Themapstep is skipped.orElsesupplies"No city". - For
"c9",findCustomerreturns an empty Optional.flatMapandmapare both skipped.orElsesupplies"No city".
Notice the mix of methods. addressOf returns an Optional, so it uses flatMap. Address::city returns a plain String, so it uses map. The map step is still safe if city() returns null, because map turns a null result into an empty Optional.
Short-Circuiting: Empty Stops the Chain
When any step in the chain produces an empty Optional, every later map, filter, and flatMap step is skipped. This is called short-circuiting, which means stopping early once the answer is already known. Only the final orElse (or a similar method) runs.
Short-circuiting is why the Optional version needs no if statements. The empty case is handled once, at the end.
Edge Cases to Watch
Your function must not return null
The function you pass to flatMap must return an Optional. It must never return null. If it does, flatMap throws a NullPointerException.
import java.util.Optional;
public class FlatMapNullDemo {
public static void main(String[] args) {
Optional<String> word = Optional.of("hi");
try {
word.flatMap(w -> null);
} catch (NullPointerException e) {
System.out.println("flatMap rejected a null result");
}
Optional<String> safe = word.flatMap(w -> Optional.empty());
System.out.println(safe.isPresent()); // false
}
}map and flatMap treat null differently
This difference surprises many beginners:
| Situation | `map` | `flatMap` |
|---|---|---|
| Function returns `null` | Gives an empty Optional | Throws `NullPointerException` |
| Function returns an Optional | Gives a nested Optional | Gives that Optional |
| Starting Optional is empty | Function not called | Function not called |
Wrapping a method that might return null
Sometimes the method you need is not yours, and it returns null instead of an Optional. You can still use flatMap by wrapping the call with Optional.ofNullable:
.flatMap(c -> Optional.ofNullable(c.address()))This does the same job as calling .map(Customer::address). Both are correct. Many developers prefer map here because it is shorter. Use flatMap when you already have a method that returns Optional.
Chaining More Than Two Lookups
You can chain as many flatMap calls as you need. Each one adds a single line, not a new level of nesting. Here is a three-step lookup: order, then customer, then address.
import java.util.Map;
import java.util.Optional;
public class ThreeStepDemo {
record Address(String city) {}
record Customer(String name, Address address) {}
record Order(String id, String customerId) {}
static final Map<String, Order> ORDERS =
Map.of("o1", new Order("o1", "c1"));
static final Map<String, Customer> CUSTOMERS =
Map.of("c1", new Customer("Lin", new Address("Oslo")));
static Optional<Order> findOrder(String id) {
return Optional.ofNullable(ORDERS.get(id));
}
static Optional<Customer> customerOf(Order o) {
return Optional.ofNullable(CUSTOMERS.get(o.customerId()));
}
static Optional<Address> addressOf(Customer c) {
return Optional.ofNullable(c.address());
}
public static void main(String[] args) {
String city = findOrder("o1")
.flatMap(ThreeStepDemo::customerOf)
.flatMap(ThreeStepDemo::addressOf)
.map(Address::city)
.orElse("Unknown");
System.out.println(city); // Oslo
}
}The chain reads from top to bottom like a sentence: find the order, get its customer, get their address, read the city, or else say "Unknown."
Summary
- Use
flatMapwhen the function you call returns an Optional. mapwould wrap that result again and give youOptional<Optional<T>>.- An empty Optional anywhere in the chain skips all later steps.
- The function passed to
flatMapmust return an Optional, nevernull.
Exercise
A method Optional<Phone> phoneOf(Customer c) exists. You have an Optional<Customer> customer. What type do you get from customer.map(this::phoneOf), and which call gives you an Optional<Phone> instead?
Show answer
customer.map(this::phoneOf) gives Optional<Optional<Phone>>, because map wraps the Optional that phoneOf returns. Use customer.flatMap(this::phoneOf) to get Optional<Phone>.
Exercise
In the FlatMapChainDemo program, what does cityFor("c2") print, and which steps of the chain actually run?
Show answer
It prints "No city". findCustomer runs and finds Sam. flatMap runs and calls addressOf, which returns an empty Optional because Sam's address is null. The map(Address::city) step is skipped, and orElse supplies "No city".
Exercise
What happens when you run Optional.of("x").flatMap(s -> null), and how would you fix the lambda so it means "no result"?
Show answer
It throws a NullPointerException, because flatMap does not accept a null return value from its function. Fix it by returning an empty Optional: Optional.of("x").flatMap(s -> Optional.empty()).
Exercise
You need to chain findUser(id) (returns Optional<User>), User::email (returns a String that may be null), and String::toLowerCase. Write the chain, ending with a default of "none". Choose map or flatMap at each step.
Show answer
findUser(id).map(User::email).map(String::toLowerCase).orElse("none"). Both steps use map because User::email and String::toLowerCase return plain values, not Optionals. If email returns null, map produces an empty Optional, so the result is "none".