map, flatMap and filter on Optional
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)You can work on the value inside an Optional without taking it out. map, filter and flatMap each return a new Optional, so they chain into one readable line, and an empty box simply passes through every step untouched.
map: change the value inside the box
map(function) applies a function to the value and puts the result in a new Optional. Optional.of(" riya ").map(String::trim) gives Optional[riya]. The function is a Function<T, R>: a lambda that takes one value and returns another, possibly of a different type, like name -> name.length().
Example 1 · map: transform the value, skip the empty box
import java.util.Optional;
public class MapDemo { public static void main(String[] args) { Optional<String> typed = Optional.of(" rahul sharma ");
Optional<String> clean = typed.map(String::trim); Optional<String> upper = clean.map(s -> s.toUpperCase()); Optional<Integer> length = clean.map(String::length); System.out.println(clean + " " + upper + " " + length);
Optional<String> nothing = Optional.empty(); System.out.println(nothing.map(s -> { System.out.println("never printed"); return s.toUpperCase(); }));
Optional<String> toNull = typed.map(s -> null); System.out.println("map to null gives " + toNull); }}Optional[rahul sharma] Optional[RAHUL SHARMA] Optional[12] Optional.empty map to null gives Optional.empty
What this code does
mapreturns a new Optional each time, and the type can change:Optional<String>becomesOptional<Integer>withString::length.- On an empty Optional the function is never called, so "never printed" does not appear. A function that returns
nullgives an empty Optional, notOptional[null].
If the Optional is empty, map does not call the function at all; it returns an empty Optional. If the function returns null, map also returns an empty Optional. So you can chain steps without a single null check: each step runs only when there is something to work on.
Trace the code
Watch map on a full and an empty box
Step through and compare the two boxes.
Variables
- name
- Optional[asha]
Output
(nothing printed yet)Line 5A full box holds the text asha.
filter: keep the value only if it passes a check
filter(predicate) keeps the value if the test returns true and gives an empty Optional if it returns false. A Predicate<T> is a lambda that takes a value and returns a boolean, like otp -> otp.length() == 6.
Example 2 · filter: keep only values that pass a check
import java.util.Optional;
public class FilterDemo { static Optional<String> validOtp(String typed) { return Optional.ofNullable(typed) .map(String::trim) .filter(s -> s.length() == 6) .filter(s -> s.chars().allMatch(Character::isDigit)); }
public static void main(String[] args) { System.out.println(validOtp(" 482913 ")); System.out.println(validOtp("48291")); System.out.println(validOtp("48a913")); System.out.println(validOtp(null));
Optional<Integer> age = Optional.of(17); String vote = age.filter(a -> a >= 18).map(a -> "can vote").orElse("cannot vote yet"); System.out.println("Age 17: " + vote); }}Optional[482913] Optional.empty Optional.empty Optional.empty Age 17: cannot vote yet
What this code does
- Each
filtereither keeps the box as it is or empties it. The OTP must pass both checks: six characters, and all of them digits. - Four different problems (too short, a letter,
null, or underage) all end as an empty Optional, and oneorElseat the end handles them.
An empty Optional stays empty and the test is not run. This turns "find it, then check it" into one chain: findStudent(roll).filter(s -> s.attendance() >= 75) is present only for a student who exists and may sit the exam.
flatMap: when the method already returns an Optional
Suppose user.getAddress() returns Optional<Address>. Then findUser(id).map(User::getAddress) wraps that Optional in another one: Optional<Optional<Address>>, a box inside a box. Nothing useful can be done with that type.
Example 3 · map versus flatMap: the box inside a box
import java.util.HashMap;import java.util.Map;import java.util.Optional;
public class FlatMapDemo { static Map<String, String> mentorOf = new HashMap<>(); static Map<String, String> cabinOf = new HashMap<>();
static Optional<String> findMentor(String student) { return Optional.ofNullable(mentorOf.get(student)); }
static Optional<String> findCabin(String mentor) { return Optional.ofNullable(cabinOf.get(mentor)); }
public static void main(String[] args) { mentorOf.put("Aman", "Dr Iyer"); mentorOf.put("Bina", "Dr Khan"); cabinOf.put("Dr Iyer", "C-204");
Optional<Optional<String>> boxInBox = findMentor("Aman").map(m -> findCabin(m)); System.out.println("map: " + boxInBox);
Optional<String> cabin = findMentor("Aman").flatMap(m -> findCabin(m)); System.out.println("flatMap: " + cabin);
System.out.println("Bina: " + findMentor("Bina").flatMap(FlatMapDemo::findCabin)); System.out.println("Chirag: " + findMentor("Chirag").flatMap(FlatMapDemo::findCabin)); }}map: Optional[Optional[C-204]] flatMap: Optional[C-204] Bina: Optional.empty Chirag: Optional.empty
What this code does
findCabinalready returns an Optional, somapwraps it again:Optional[Optional[C-204]].flatMapreturns the inner Optional directly.- Bina has a mentor but the mentor has no cabin; Chirag has no mentor at all. Both end as
Optional.empty, and the chain did not need a singleif.
flatMap(function) is for functions that return an Optional themselves. It calls the function and returns its Optional directly, without wrapping it again. The rule is simple: if the function returns a plain value, use map; if it returns an Optional, use flatMap.
map(s -> s.getName()): function returnsString, resultOptional<String>.map(u -> u.getAddress()): function returnsOptional<Address>, resultOptional<Optional<Address>>.flatMap(u -> u.getAddress()): same function, resultOptional<Address>.
or (Java 9): try a second source
or(supplier) returns the same Optional if it is present. If it is empty, it calls the supplier, which must return another Optional, and returns that. Like orElseGet, the supplier runs only when needed.
Example 4 · or: try the cache, then the database
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
public class OrDemo { static Map<Integer, String> cache = new HashMap<>(); static Map<Integer, String> database = new HashMap<>();
static Optional<String> fromCache(int roll) { System.out.print("[cache] "); return Optional.ofNullable(cache.get(roll)); }
static Optional<String> fromDatabase(int roll) { System.out.print("[db] "); return Optional.ofNullable(database.get(roll)); }
public static void main(String[] args) { cache.put(1, "Om"); database.put(1, "Om"); database.put(2, "Pari");
for (int roll : List.of(1, 2, 3)) { String name = fromCache(roll) .or(() -> fromDatabase(roll)) .map(String::toUpperCase) .orElse("not found"); System.out.println(roll + " -> " + name); } }}[cache] 1 -> OM [cache] [db] 2 -> PARI [cache] [db] 3 -> not found
What this code does
orkeeps the cached Optional when it is present; the database is not even asked for roll 1. For rolls 2 and 3 the cache is empty, so the supplier runs and its Optional takes over.- Because
orreturns an Optional (unlikeorElseGet), the chain can continue withmapand finish with oneorElsefor the case where both sources are empty.
The difference from orElseGet is the result type. orElseGet ends the chain with a plain value. or keeps an Optional, so you can try a cache, then a database, then a backup, and still decide at the end what to do if all of them are empty: findInCache(id).or(() -> findInDb(id)).orElse("Unknown").
Replacing nested null checks
Getting a user's city in old code needs a check at every level: is the user null? Is the address null? Is the city null?
Example 5 · Nested null checks versus one Optional chain
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
class Address { final String city;
Address(String city) { this.city = city; }
Optional<String> getCity() { return Optional.ofNullable(city); }}
class User { final String name; final Address address;
User(String name, Address address) { this.name = name; this.address = address; }
Optional<Address> getAddress() { return Optional.ofNullable(address); }}
public class CityChainDemo { static Map<String, User> users = new HashMap<>();
// Old way: a check at every level static String cityOld(String id) { User u = users.get(id); if (u != null) { Address a = u.address; if (a != null) { String c = a.city; if (c != null) { return c.toUpperCase(); } } } return "UNKNOWN"; }
// New way: one chain static String cityNew(String id) { return Optional.ofNullable(users.get(id)) .flatMap(User::getAddress) .flatMap(Address::getCity) .map(String::toUpperCase) .orElse("UNKNOWN"); }
public static void main(String[] args) { users.put("u1", new User("Asha", new Address("Pune"))); users.put("u2", new User("Bala", new Address(null))); users.put("u3", new User("Chitra", null));
for (String id : List.of("u1", "u2", "u3", "u9")) { System.out.println(id + ": old=" + cityOld(id) + " new=" + cityNew(id)); } }}u1: old=PUNE new=PUNE u2: old=UNKNOWN new=UNKNOWN u3: old=UNKNOWN new=UNKNOWN u9: old=UNKNOWN new=UNKNOWN
What this code does
- Both methods give the same answers for all four cases: a full address, an address without a city, a user without an address, and no user at all.
getAddressandgetCityreturn Optionals, so they needflatMap.String::toUpperCasereturns a plainString, so it needsmap. The singleorElsereplaces the threeifblocks and the finalreturn.- Why the chain: each step handles the empty case by itself, so the real logic (find, then get the city, then upper-case it) is visible without three levels of
if.
That is three nested if blocks for one line of real work, and missing any one of them means an NPE.
With Optional-returning getters, the same logic is one chain: findUser(id).flatMap(User::getAddress).flatMap(Address::getCity).map(String::toUpperCase).orElse("UNKNOWN"). Each step runs only if the step before it found something. The first empty step makes the rest pass through, and orElse handles every missing case at once.
Next step
Check your understanding
12 quick questions