Skip to content
Tutorials Center
My learning

Topics

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.

Java
findUser("ann").ifPresent(u -> System.out.println(u.name()));

Try it

Java ifPresent and ifPresentOrElse

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.

Java Replacing null checks

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

Java
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, use map, or orElse*, instead.
  • Prefer it to isPresent() plus get(). The two-step pattern is just a null check with extra steps; ifPresent states the intent and cannot hit NoSuchElementException.
  • No checked exceptions inside the lambda, because Consumer and Runnable cannot 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::stream then forEach.
  • Thread safety. An Optional is immutable, so reading it from several threads is safe; the action you pass is your responsibility.