Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.orElseGet: practical reference

Optional.orElseGet: practical reference: Optional.orElseGet(supplier) returns the present value and invokes the supplier only for an empty Optional, returning its result.

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

Syntax

Optional.orElseGet(...)

Optional.orElseGet(supplier) returns the present value and invokes the supplier only for an empty Optional, returning its result.

Use it to lazily create an expensive, state-dependent, or side-effecting default value.

The supplier may run on every separate orElseGet call on an empty Optional; the method does not cache its result.

A null supplier throws NullPointerException only when the Optional is empty; the supplier itself may return null, which becomes the result.

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 {
        var value = java.util.Optional.<String>empty().orElseGet(() -> "computed");
        System.out.println(value);
    }
}

Result

computed

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

Sources