Part 09 / Topic 9 of 10
Optional: say "might be missing" in the type
Before Optional, "no result" was usually spelled null — and nothing in a method's signature warned you that it might happen. Optional<T> is a small box that either holds exactly one value, or holds nothing; the type itself now tells every caller "check before you use this."
static Optional<Customer> findById(String id) {
return CUSTOMERS.stream().filter(c -> c.id().equals(id)).findFirst();
}
C-01 present: true
C-99 present: false
Optional.of(value) wraps a value you know is not null; Optional.empty() is an explicitly empty box; Optional.ofNullable(value) is the bridge from "a value that might be null" (often from older code or a library) into an Optional — it is empty if value is null, present otherwise.
Reading the value safely
map transforms the value only if it is present, and does nothing (stays empty) otherwise — so a chain of map calls never throws for a missing value:
String cityOfC01 = findById("C-01").map(Customer::city).orElse("unknown"); // Pune
String cityOfC99 = findById("C-99").map(Customer::city).orElse("unknown"); // unknown
If the field you are mapping to can itself be null (not every field is guaranteed non-null), map would hand you back an Optional holding null, which defeats the point. Use flatMap with Optional.ofNullable to flatten that one level:
String emailOfC02 = findById("C-02")
.flatMap(c -> Optional.ofNullable(c.email()))
.orElse("no email on file");
.filter(predicate) keeps the value only if it passes a check, and empties the Optional otherwise — useful for "found, but does it also satisfy this rule?" .ifPresentOrElse(whenPresent, whenEmpty) replaces the old isPresent() + get() pair with one call that cannot forget the empty case:
findById("C-99").ifPresentOrElse(
c -> System.out.println("found: " + c.city()),
() -> System.out.println("not found"));
.orElseThrow(() -> new SomeException(...)) turns "empty" into your own exception, right at the point the value was needed — much easier to debug than a NullPointerException three calls later with no context.
orElse vs. orElseGet
orElse(value) always builds its argument, present or not, because Java evaluates a method's arguments before calling it. orElseGet(supplier) only calls the Supplier if the Optional is actually empty.
findById("C-01").orElse(expensiveDefault("orElse")); // runs expensiveDefault() anyway
findById("C-01").orElseGet(() -> expensiveDefault("orElseGet")); // does NOT run it: C-01 is present
expensiveDefault() built by orElse
Only one line prints — proof that orElseGet's lambda never ran, because findById("C-01") was present both times. Prefer orElseGet whenever building the fallback does real work (a database call, a calculation); reach for orElse only when the fallback is already sitting in a variable or a cheap literal.
🔍 Going deeper:
Optionalis meant for return types, not everywhere. Avoid it as a field type (it does not implementSerializableand adds no value stored in an object), as a method parameter (overloading without the wrapper is clearer), or inside a collection (List<Optional<T>>— filter the missing ones out instead). And never call.get()without checking first; it throwsNoSuchElementExceptionon an emptyOptional, which is exactly the crashOptionalexists to make you think about before it happens, not after.
Full program: examples/OptionalDemo.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.