Run one action if a value is present, and a fallback action if it is not.
Optional<String> found = Optional.of("data");
Optional<String> missing = Optional.empty();
found.ifPresentOrElse(
v -> System.out.println("got: " + v),
() -> System.out.println("nothing"));
missing.ifPresentOrElse(
v -> System.out.println("got: " + v),
() -> System.out.println("nothing"));
got: data
nothing
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-26