Course contentsShow
← Java
Lesson 1806 of 2,87037. Optional for Null SafetyFree lesson

When to Use flatMap vs map

Master the decision between map for simple transformations and flatMap for operations that themselves return Optional.

When to Use flatMap vs map

What you'll learn: How to confidently choose between map and flatMap when working with Optional transformations.


Now that you understand both map and flatMap, the key question becomes: when do I use which? The decision is straightforward once you focus on what your transformation function returns.

The Decision Rule

Use map when your transformation function returns a plain value:

Optional<String> name = Optional.of("Alice");
Optional<Integer> length = name.map(String::length); // returns int

The function String::length returns a simple int, so map automatically wraps it in Optional<Integer>.

Use flatMap when your transformation function already returns an Optional:

Optional<String> name = Optional.of("Alice");
Optional<User> user = name.flatMap(userRepository::findByName); // returns Optional<User>

Here, findByName already returns Optional<User>. Using map would create Optional<Optional<User>> (nested). Using flatMap flattens it to just Optional<User>.

The Pattern to Recognize

Ask yourself: Does my transformation method return Optional?

  • No → Use map
  • Yes → Use flatMap

Real-World Example

Optional<Order> order = findOrderById(123);

// map: getCustomerId returns plain Long
Optional<Long> customerId = order.map(Order::getCustomerId);

// flatMap: findCustomerById returns Optional<Customer>
Optional<Customer> customer = order.flatMap(o -> findCustomerById(o.getCustomerId()));

The transformation dictates the method: plain return values pair with map, Optional-returning methods pair with flatMap.

Key Takeaway: Use map for transformations that return plain values; use flatMap for transformations that return Optional, avoiding nested Optional structures.