Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.ifPresentOrElse: practical reference

Optional.ifPresentOrElse: practical reference: Optional.ifPresentOrElse(action, emptyAction) invokes the Consumer with the present value or runs the Runnable when absent; exactly one branch is selected.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Optional.ifPresentOrElse(...)

Optional.ifPresentOrElse(action, emptyAction) invokes the Consumer with the present value or runs the Runnable when absent; exactly one branch is selected.

Use it when both success and absence require side effects, such as recording a result or a failed-lookup metric.

The method returns void and an exception from the selected branch propagates; do not expect both callbacks or use them to map a value.

Null causes NullPointerException only for the callback selected by the Optional state: action when present or emptyAction when absent; the other callback is not invoked.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        java.util.Optional.<String>empty().ifPresentOrElse(System.out::println, () -> System.out.println("empty"));
    }
}

Result

empty

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources