Optional.ifPresent()
Runs an action only if a value is present.
Available since: Java 8
Syntax
void ifPresent(Consumer<? super T> action)
void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)Parameters
| Parameter | Type | Description |
|---|---|---|
| action | Consumer<? super T> | The action on the value if it is present. |
| emptyAction | Runnable | The action if there is no value (only for `ifPresentOrElse`, Java 9). |
Examples
An action and a fallback branch:
void main() {
Optional<String> user = Optional.of("Anna");
user.ifPresent(u -> IO.println("Hello, " + u));
Optional.<String>empty().ifPresentOrElse(
u -> IO.println("Hello, " + u),
() -> IO.println("Hello, guest"));
}Output:
Hello, Anna
Hello, guestNotes
If there is no value, ifPresent() simply does nothing. The method returns nothing; to get a value with a fallback use orElse().
See also
- Optional.isPresent() — Checks whether an `Optional` holds a value.
- Consumer — An action that takes a value and returns nothing.
- Runnable — A task with no arguments and no result.
Related recipes
In the tutorial
- Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.