Skip to content

Chapter 30 of 37

Optional

Model possibly absent return values with safe mapping, composition, and fallbacks.

28 minutes 10 quick checksBy Subha Prasad
Lesson 30 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Optional<T> makes absence explicit for return values. It must never contain null and is usually inappropriate for fields, method parameters, collections, or serialization models.

Compose absence

String label = repository.find(id)
    .map(User::displayName)
    .filter(name -> !name.isBlank())
    .orElseGet(() -> "Unknown " + id);

Use map, flatMap, filter, ifPresent, or, and lazy orElseGet. orElse evaluates its fallback eagerly. Avoid unguarded get; use orElseThrow when absence violates the caller’s contract. An empty collection already represents no elements, so do not wrap it in Optional.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes Optional?
Which Java term matches this description: A container representing a present or absent non-null value.
Which statement best describes map?
Which Java term matches this description: An Optional operation transforming a present value.
Which statement best describes flatMap?
Which Java term matches this description: An Optional operation composing a function that already returns Optional.
Which statement best describes orElseGet?
Which Java term matches this description: A lazy fallback supplier used only when the Optional is empty.
Which statement best describes ifPresent?
Which Java term matches this description: An operation running a Consumer only for a present value.

0 of 10 checks passed

Your progress is saved on this device.