Optional: handling absence
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,filterandflatMapto transform the valueorElse(default),orElseGet(supplier)andorElseThrow()(Java 10)ifPresent,ifPresentOrElse(Java 9) andisEmpty()(Java 11)
Spring Data's findById returns an Optional.
Example
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
Know these first
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.