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.
0 of 10 checks passed
Your progress is saved on this device.