Skip to content
Ameen Abozaid
BEG-037

Optional

  • 4 Lessons
  • 46 min of reading
  • 1.5 h practice (estimate)
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

  1. Return Optional from a method that may not find a result.
  2. Transform and unwrap with map, filter, orElse, orElseGet, orElseThrow.
  3. State where Optional should not be used (fields, parameters, collections).

Lessons

  1. 01The billion-dollar mistake: null12 min read
  2. 02Using Optional well11 min read
  3. 03Optional anti-patterns12 min read
  4. 04Demo: making findById return Optional11 min read

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)

IDOutcomeTask
BEG-037-EX011Write Optional<String> firstLongWord(List<String> words, int min) that returns the first word with at least min letters.
BEG-037-EX022Given Optional<String> name, print it upper-cased or "guest", and write a second version that throws IllegalStateException("name missing").
BEG-037-EX033Fix 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 with filter(...).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 plain Integer/int or use overloads; return List<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.

  1. 1Optional<T> is best used as:O1
  2. 2Which creates an empty Optional?O1
  3. 3Optional.of(null) will:O1
  4. 4opt.orElse("x") returns:O2
  5. 5Which computes its default only when needed?O2
  6. 6To throw your own exception when empty:O2
  7. 7opt.map(String::length) returns:O2
  8. 8Calling get() on an empty Optional:O3
  9. 9A method that finds no orders should return:O3
  10. 10Which is an anti-pattern?O3

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).

Type to search levels, phases, modules and lessons.