Optional.ifPresentOrElse()
Code Comparison
Optional<User> user = findUser(id);
if (user.isPresent()) {
greet(user.get());
} else {
handleMissing();
}
findUser(id).ifPresentOrElse(
this::greet,
this::handleMissing
);
Why the modern way wins
๐
Single expression
Both cases handled in one method call.
๐ซ
No get()
Eliminates the dangerous isPresent() + get() pattern.
๐
Fluent
Chains naturally after findUser() or any Optional-returning method.
Old Approach
if/else on Optional
Modern Approach
ifPresentOrElse()
JDK Support
Optional.ifPresentOrElse()
Available
Widely available since JDK 9 (Sept 2017)
How it works
ifPresentOrElse() takes a Consumer for the present case and a Runnable for the empty case. It avoids the isPresent/get anti-pattern.
Related Documentation
Proof