orElse runs its argument even when it isn't needed
The first call computed a default and threw it away. With a database lookup instead of a print, that's a real cost on every call.
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
orElse on a present value:
(computing default...)
result cached
orElseGet on a present value:
result cached
orElseGet on an empty value:
(computing default...)
result default
default computed 2 times