Optional
On this page 8 topics
Overview
Topics
- Optional creation
- transformations
- appropriate usage
Learn first
46 min of reading · 1.5 h of practice (estimate)
Learning outcomes
- Return
Optionalfrom a method that may not find a result. - Transform and unwrap with
map,filter,orElse,orElseGet,orElseThrow. - State where
Optionalshould not be used (fields, parameters, collections).
Lessons
Lab and exercises
Lab
BEG-037-LAB1 · Safe lookups
Outcomes: 1–3 · Time: ~1 h Change findById in the generic repository (BEG-031) to return Optional and update all callers. Acceptance: no .get() without a check.
Exercises (assessment: three exercises)
| ID | Outcome | Task |
|---|---|---|
| BEG-037-EX01 | 1 | Write Optional<String> firstLongWord(List<String> words, int min) that returns the first word with at least min letters. |
| BEG-037-EX02 | 2 | Given Optional<String> name, print it upper-cased or "guest", and write a second version that throws IllegalStateException("name missing"). |
| BEG-037-EX03 | 3 | Fix these: a class with an Optional<String> field, a method with an Optional<Integer> parameter, a method returning Optional<List<Order>>. |
Show solutions
- EX01
for (String w : words) if (w.length() >= min) return Optional.of(w); return Optional.empty();(or a stream withfilter(...).findFirst()). - EX02
name.map(String::toUpperCase).orElse("guest");name.orElseThrow(() -> new IllegalStateException("name missing")). - EX03 Make the field a plain
String(possibly null, documented) or keep it as a normal value; take a plainInteger/intor use overloads; returnList<Order>and an empty list when nothing is found. - Outcome 1 is also covered by the lab and quiz Q01–Q03.
Quiz
Outcomes: O1 returning Optional · O2 transforming and unwrapping · O3 where not to use it.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Three exercises BEG-037-EX01 to EX03 plus the lab. Pass: all three exercises correct and the lab has no unchecked .get().
Common mistakes
optional.get() unconditionally; Optional fields.
Assessment
3 exercises.
Career relevance
Spring Data return types (JNR-029).