Stage 4: Modern Java, lesson 4 of 7

Optional: handling absence

Intermediate3 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Optional<T> (Java 8) holds either a value or nothing. It makes "this might be missing" visible in the method signature.

Create one with Optional.of(x), Optional.ofNullable(x) or Optional.empty().

Use it fluently:

  • map, filter and flatMap to transform the value
  • orElse(default), orElseGet(supplier) and orElseThrow() (Java 10)
  • ifPresent, ifPresentOrElse (Java 9) and isEmpty() (Java 11)

Spring Data's findById returns an Optional.

Example

Java
Optional<User> user = userRepository.findById(id);

String city = user
    .map(User::getAddress)
    .map(Address::getCity)
    .orElse("Unknown");

User u = userRepository.findById(id)
    .orElseThrow(() -> new NotFoundException("User " + id));

user.ifPresentOrElse(
    x -> log.info("Found {}", x.getName()),
    () -> log.warn("No user {}", id));          // Java 9+

Common mistake

Calling optional.get() without checking. It throws NoSuchElementException, which is just a different crash. Prefer orElseThrow() with a clear message.

Under the hood

Optional was designed as a return type. Avoid it for fields (it isn't Serializable), method parameters and collections (return an empty list instead). orElse(expensive()) always evaluates its argument; use orElseGet(() -> expensive()) when the default is costly to build.

Check yourself

Which call throws NoSuchElementException when the Optional is empty?

How this connects

Where this leads

You've reached the end of this thread. Try a learning path for what's next.

Part of Job-ready backend developer.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.