Optional creation and transformation
What you will learn
Optional<T> represents a successful lookup that may have no value. It makes callers confront absence explicitly instead of accidentally dereferencing null. An empty Optional is still a valid object.
- Choose of, ofNullable or empty for a known input contract.
- Transform a present value with map, filter or flatMap.
- Explain the difference between an empty Optional and a null reference.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
A missing inventory lookup
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> stock = Map.of("P1", 0, "P2", 7); Optional<Integer> found = Optional.ofNullable(stock.get("P1")); Optional<Integer> missing = Optional.ofNullable(stock.get("P9")); System.out.println(found.isPresent()); System.out.println(found.orElseThrow()); System.out.println(missing.isEmpty()); System.out.println(Optional.<Integer>empty().isEmpty()); System.out.println(Optional.of(7).isPresent()); }}Expected output:
true0truetruetrueZero is a valid stock count, not a missing item. Map.of disallows null values, so null from get means no mapping.
Creation and presence
Use Optional.of(value) when null would violate the contract; it rejects null. Use Optional.ofNullable(value) at a nullable boundary, such as a legacy lookup that returns null for missing keys. Optional.empty() intentionally represents absence. Optional cannot contain null as a present value. Use isPresent() or isEmpty() to check state, not identity comparisons. Java 11 added isEmpty. Optional is value-based: equal containers are interchangeable, so do not lock on them or assume an empty instance is a singleton. Never return null from an Optional-returning method.
Transform and filter
A map function takes the contained value and returns an ordinary result; a null result becomes empty. filter keeps the present value only if its predicate accepts it. An empty container skips these callbacks. flatMap is for functions already returning an Optional: it avoids a nested Optional and rejects a null Optional result. Neither mapping operation catches exceptions from the function. Pass valid non-null functions even if you expect absence.
Choosing a return contract
A search that legitimately may find nothing is a good candidate for Optional. A collection-returning search can instead return an empty collection when there are no matches. Do not wrap every field or parameter automatically: choose a contract appropriate to the domain and serialization or framework boundary. Optional is not a guarantee of immutable contained data. Avoid get() unless presence is guaranteed; orElseThrow expresses a required result more clearly.
Normalize and validate a label
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var result = Optional.of(" Bolt ").map(String::strip).filter(s -> !s.isEmpty()); System.out.println(result.orElseThrow()); System.out.println(Optional.of(" ").map(String::strip).filter(s -> !s.isEmpty()).isEmpty()); System.out.println(Optional.of("bolt").map(s -> (String)null).isEmpty()); }}Expected output:
BolttruetrueWhitespace normalization precedes validation; map converts a null result to absence.
Join two lookups without nesting
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,String> skuByAlias = Map.of("bolt", "P1", "nut", "P9"); Map<String,Integer> stock = Map.of("P1", 12); java.util.function.Function<String,Optional<Integer>> lookup = sku -> Optional.ofNullable(stock.get(sku)); for (String alias : List.of("bolt", "nut", "unknown")) { var result = Optional.ofNullable(skuByAlias.get(alias)).flatMap(lookup); System.out.println(alias + ":" + result.map(Object::toString).orElse("missing")); } }}Expected output:
bolt:12nut:missingunknown:missingflatMap propagates absence from either lookup; map alone would create Optional<Optional<Integer>>.
Observe skipped callbacks and equality
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { int[] calls = {0}; var empty = Optional.<String>empty().map(s -> { calls[0]++; return s.length(); }); System.out.println(empty.isEmpty() + ":" + calls[0]); System.out.println(Optional.of("A").equals(Optional.of(new String("A")))); }}Expected output:
true:0trueThe mapper is skipped for an empty container. Equality compares contained values, not wrapper identity.
Common mistakes
Do not write Optional.of(nullableValue), return null from a lookup declared Optional, or compare with Optional.empty() using ==. Do not use map to hide a broken mapper that should return a non-null result; validate that boundary explicitly. If a null result has a different meaning from not found, preserve it with a richer domain result.
Practice
Given stock {A:0, B:8}, query A, B and C, filter for positive quantity and print either the quantity or unavailable. Explain why this operation intentionally collapses zero and missing into the same result.
Expected output:
A:unavailableB:8C:unavailableCompare your answer with the manual practice criteria.
Official reading: Java SE 25 Optional · Objects. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optional creation and transformation — knowledge check
Original Java Optional contract and boundary questions. Java 21-compatible scope.
Which call rejects a null value?
What does map return when the mapper returns null?
Which operation avoids nested Optional when a mapper already returns Optional?
How should an empty Optional be detected?
Stock is present with value 0. What does isPresent return?