Functional error boundaries
What you will learn
Absence is not the same as a failed operation. Use Optional for a legitimate missing result, and retain errors when input is malformed or an operation cannot complete. A domain result can represent distinct expected outcomes explicitly.
- Use ifPresent, ifPresentOrElse and Optional.stream appropriately.
- Distinguish a missing value from malformed data and exceptions.
- Model expected domain outcomes with records and narrowly scoped error handling.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Report a present or missing item
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> stock = Map.of("A", 3); Optional.ofNullable(stock.get("A")).ifPresent(n -> System.out.println("Stock: " + n)); for (String id : List.of("A", "B")) { Optional.ofNullable(stock.get(id)).ifPresentOrElse(n -> System.out.println(id + ":" + n), () -> System.out.println(id + ":missing")); } }}Expected output:
Stock: 3A:3B:missingExactly one action is selected in ifPresentOrElse. No transformed value is returned.
Consume presence deliberately
ifPresent(action) executes a consumer for a present value and otherwise does nothing. ifPresentOrElse(action, emptyAction) (Java 9) chooses one of two actions. These methods return void; do not use them to calculate a transformed value. Use map for transformation. Keep side effects at a well-defined output boundary.
Integrate with streams
Optional.stream() (Java 9) gives zero elements for empty or one for present. streamOfOptionals.flatMap(Optional::stream) removes absent values without unsafe get calls. This loses the positions and identities of missing values; preserve those separately when reporting missing SKUs. An Optional reference itself must not be null. The contained object is not automatically made immutable.
Errors need their own contract
Optional does not intercept an exception thrown by a mapper or supplier. For example, Integer.parseInt throws NumberFormatException for invalid text; this does not become an empty Optional. If malformed data is a normal business outcome, catch that specific exception at the parsing boundary and return a result record with an explicit reason. A sealed result hierarchy could encode alternatives more strongly (see Chapter 15). Avoid catch-all conversions, and do not swallow unexpected service failures or programming defects.
Collect known quantities
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> stock = Map.of("A", 0, "B", 3); var requested = List.of("B", "X", "A"); var quantities = requested.stream().map(id -> Optional.ofNullable(stock.get(id))).flatMap(Optional::stream).toList(); System.out.println(quantities); System.out.println(requested.stream().filter(id -> !stock.containsKey(id)).toList()); }}Expected output:
[3, 0][X]The flattened stream retains known quantities including zero. The separate missing-key report retains identity.
A mapper can fail
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { for (String text : List.of("12", "bad")) { try { System.out.println(Optional.of(text).map(Integer::parseInt).orElseThrow()); } catch (NumberFormatException ex) { System.out.println("Invalid quantity: " + text); } } }}Expected output:
12Invalid quantity: badA parsing exception leaves the pipeline; the specific parsing error is handled outside.
Return explicit outcomes
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { enum Status { FOUND, MISSING, INVALID } record Result(Status status, Optional<Integer> quantity) { Result { Objects.requireNonNull(status); Objects.requireNonNull(quantity); if ((status == Status.FOUND) != quantity.isPresent()) throw new IllegalArgumentException("Inconsistent result"); } } java.util.function.Function<String,Result> parse = text -> { if (text == null) return new Result(Status.MISSING, Optional.empty()); try { int n = Integer.parseInt(text); return n < 0 ? new Result(Status.INVALID, Optional.empty()) : new Result(Status.FOUND, Optional.of(n)); } catch (NumberFormatException ex) { return new Result(Status.INVALID, Optional.empty()); } }; for (String input : new String[]{"0", null, "bad", "-1"}) { var r = parse.apply(input); System.out.println(r.status() + ":" + r.quantity().map(Object::toString).orElse("-")); } }}Expected output:
FOUND:0MISSING:-INVALID:-INVALID:-This local record deliberately uses Optional as a component to illustrate an explicit domain contract. The constructor rejects mismatched status and presence. For production a sealed hierarchy can avoid redundant state; Optional fields are not a universal rule.
Common mistakes
Never assume map catches exceptions. Do not remove all missing values when a reconciliation report needs their keys. Avoid Optional<Exception> as a generic substitute for meaningful error handling. A status and payload must agree; enforce invariants instead of allowing an invalid combination.
Practice
For inventory IDs A, X, B and Y with stock A=4 and B=0, print the sum of known quantities using Optional.stream and print the missing IDs in encounter order.
Expected output:
4[X, Y]Compare 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
Functional error boundaries — knowledge check
Original Java Optional contract and boundary questions. Java 21-compatible scope.
What is the return type of ifPresentOrElse?
How many elements does Optional.empty().stream() have?
What happens when a map callback throws NumberFormatException?
Why use a result status for malformed quantity?
What can be lost when flattening Optional values?