Combining map, flatMap, and filter
You'll learn how to build elegant Optional pipelines that transform, flatten, and conditionally filter values in a single fluent chain.
The Power of Composition
Now that you've learned map, flatMap, and filter individually, the real magic happens when you combine them. These methods chain naturally because each returns an Optional, allowing you to express complex null-safe transformations in a readable, declarative style.
Think of it like an assembly line: filter decides whether something continues down the line, map transforms it, and flatMap handles transformations that themselves might produce nothing.
Building a Pipeline
The typical pattern flows like this:
Optional<String> result = Optional.ofNullable(user)
.filter(u -> u.isActive()) // Only proceed if active
.map(User::getProfile) // Transform to Profile (may be null)
.flatMap(Profile::getEmail) // Profile.getEmail() returns Optional<Email>
.map(Email::getAddress) // Transform to String
.filter(addr -> addr.contains("@")) // Validate email format
.map(String::toLowerCase); // Final transformation
Each step processes the value only if it's present. If any step produces empty(), the entire chain short-circuits and returns empty().
Real-World Example
String displayName = Optional.ofNullable(getUser(id))
.filter(User::isVerified)
.flatMap(User::getNickname) // Returns Optional<String>
.filter(nick -> nick.length() >= 3)
.map(String::toUpperCase)
.orElse("GUEST");
This reads like English: "Get the user, if verified, extract their nickname if present, validate its length, uppercase it, or use GUEST."
Key Takeaway: Combining map, flatMap, and filter lets you build expressive, null-safe transformation pipelines that handle presence checks, transformations, and validations in a single declarative chain without nested if-statements or explicit null checks.