Video in progress
How do you work with Optional without writing if (x.isPresent())? Use examples of map, flatMap, filter, or and ifPresentOrElse.
Optional has its own chaining methods: map transforms the value, flatMap works with a function that returns an Optional, filter adds a condition, or supplies a fallback Optional, and ifPresentOrElse handles both cases in one place.
📖 Answer
Writing isPresent() + get() is no different from a null check. Code written as a chain is shorter and less error-prone:
// the user's city name, or "noma'lum"
String city = userRepo.findById(id)
.flatMap(User::address) // address() is Optional<Address>
.map(Address::city)
.filter(c -> !c.isBlank())
.orElse("noma'lum");
If it isn't in the cache, look in the database, and if it isn't there either, ask an external service (or, Java 9+):
Optional<Rate> rate = cache.find(code)
.or(() -> db.find(code))
.or(() -> api.fetch(code));
Handling both cases in one place:
repo.findByEmail(email).ifPresentOrElse(
u -> log.info("Topildi: {}", u.id()),
() -> log.warn("Topilmadi: {}", email));
Optional.stream() (Java 9+) is useful too: ids.stream().map(repo::findById).flatMap(Optional::stream).toList() gives only the ones that were found.
One piece of advice: if the chain grows past 5–6 steps and a lot of logic builds up inside, a method written with a plain if can be easier to read. Optional is a tool, not a goal.
Sign up to mark studied questions and save your progress.