map, flatMap and filter instead of nested null checks
Optional<T> is a box that holds either one value or nothing, used as a method's return type to say "there may be no result". Instead of returning null and hoping the caller checks, you return an Optional and the caller must decide what happens when it's empty, with orElse, orElseThrow, map and friends.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static Optional<Integer> parseAge(String s) that returns empty for non-numbers and for ages outside 0..150. Print the result for "42", "abc" and "200", using orElse(-1).
Given Map<String, String> managers (employee to manager), write a method that returns the manager's manager as Optional<String>, using ofNullable and map. Test it on a three-level chain and on someone at the top.
From List.of("7", "x", "12", "", "5"), use your parseAge and flatMap(Optional::stream) to print the sum of the valid ages.
Explain it without notes
Why was Optional added, and what is it meant to be used for?
What's the difference between orElse and orElseGet?
When do you use map and when flatMap on an Optional?
Where should you not use Optional, and why?
Expected output
PUNE | PUNE
UNKNOWN | UNKNOWN
UNKNOWN | UNKNOWN
UNKNOWN | UNKNOWN
pin starts with 41: true
pin starts with 56: false
map instead of flatMap: Optional[Optional[Address[city=Pune, pin=411001]]]