Java Reference ยท Streams and Functional
Java Optional.ifPresent() and ifPresentOrElse()
Reference for Java Optional.ifPresent(), ifPresentOrElse(), isPresent() and isEmpty(): run code only when a value exists, with examples and common mistakes.
Optional.ifPresent(consumer) runs an action on the value if there is one, and does nothing if the Optional is empty. It replaces the familiar if (x != null) { ... } block when the work is a side effect: printing, adding to a list, calling a setter.
ifPresentOrElse(consumer, runnable) (Java 9) adds an else branch that runs when the Optional is empty. For simply checking, isPresent() and isEmpty() (Java 11) return booleans.
findUser("ann").ifPresent(u -> System.out.println(u.name()));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public void ifPresent(Consumer<? super T> action) public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) public boolean isPresent() public boolean isEmpty()
| Parameter | Description |
|---|---|
action |
Receives the value if one is present. |
emptyAction |
Runs with no arguments if the Optional is empty. |
Returns: ifPresent and ifPresentOrElse return nothing (void); isPresent() returns true when a value exists; isEmpty() is its opposite (since Java 11).
Throws: NullPointerException if action is null and a value is present, or if emptyAction is null and the Optional is empty. Exceptions thrown by the action propagate unchanged.
Usage notes
- Returns void. You cannot chain after
ifPresent. If you need a result, usemap, ororElse*, instead. - Prefer it to
isPresent()plusget(). The two-step pattern is just a null check with extra steps;ifPresentstates the intent and cannot hitNoSuchElementException. - No checked exceptions inside the lambda, because
ConsumerandRunnablecannot declare them. Wrap or handle them inside. - Side effects only. Use it when "do something if there is a value" is the whole point. For "get a value or fall back", use
optional-get-orelse. - Java 8 had no else branch. Code that must run on old releases needs
if (opt.isPresent()) { ... } else { ... }. - Streams of Optionals. To act on the present values only, flatten with
Optional::streamthenforEach. - Thread safety. An Optional is immutable, so reading it from several threads is safe; the action you pass is your responsibility.
Related
optional-of,optional-map,optional-get-orelse,fi-consumer- Lessons: Optional, Lambdas