Handling the Empty Case: Introduction to ifPresentOrElse
You'll learn how to handle both present and empty Optional scenarios in a single, elegant call.
The Gap Left by ifPresent
You've learned how ifPresent() elegantly consumes a value when present, but what about when the Optional is empty? Until now, you've had to write separate code blocks or use orElse methods for that scenario. The ifPresentOrElse() method fills this gap by letting you specify actions for both cases in one call.
What Is ifPresentOrElse?
Think of ifPresentOrElse() as a complete if-else statement wrapped into a single method. It takes two arguments:
- A Consumer: executed when a value is present (just like
ifPresent()) - A Runnable: executed when the Optional is empty (the new part!)
The signature looks like this:
void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
Why This Matters
Previously, you might have written:
if (optionalUser.isPresent()) {
System.out.println("User: " + optionalUser.get());
} else {
System.out.println("No user found");
}
With ifPresentOrElse(), this becomes:
optionalUser.ifPresentOrElse(
user -> System.out.println("User: " + user),
() -> System.out.println("No user found")
);
Notice the empty case handler is a Runnable (zero parameters) because there's no value to work with when the Optional is empty.
Key Takeaway: ifPresentOrElse() provides a clean, functional way to handle both the present and empty cases of an Optional in a single method call, eliminating the need for explicit conditional logic while maintaining readability.