ifPresentOrElse Signature: Consumer and Runnable
What You'll Learn
You'll understand the two functional interface parameters that ifPresentOrElse requires and why each serves a distinct purpose.
The Two-Parameter Structure
The ifPresentOrElse method takes two separate functional interfaces as arguments:
- A
Consumer<T>— executed when the Optional contains a value - A
Runnable— executed when the Optional is empty
This signature looks like:
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
Why Two Different Types?
The key insight is that these parameters handle fundamentally different scenarios:
-
Consumer<T>receives the unwrapped value as input. It's a function that accepts one argument and returns nothing. You use this to do something with the value. -
Runnabletakes no parameters at all. It's just a block of code that executes. You use this to handle the absence of a value—and since there's no value, there's nothing to pass in.
Think of it like a fork in the road: if there's treasure (a present value), the Consumer gets to examine and use it. If the chest is empty, the Runnable kicks in with a backup plan—but it has nothing to work with, so it takes no parameters.
optional.ifPresentOrElse(
value -> System.out.println("Found: " + value), // Consumer
() -> System.out.println("Nothing found") // Runnable
);
The first lambda receives value, the second receives nothing.
Key Takeaway: ifPresentOrElse uses a Consumer to process present values (receives the value) and a Runnable to handle empty cases (receives nothing), matching the nature of each scenario.