Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.orElseGet()

Returns the value, or calls a function to create a fallback.

Available since: Java 8

Syntax

T orElseGet(Supplier<? extends T> supplier)

Parameters

ParameterTypeDescription
supplierSupplier<? extends T>A function that creates the fallback value.

Return value

TThe value from the `Optional`, or the result of `supplier`.

Examples

The function is called only when the value is absent:

String loadDefault() {
    IO.println("loading default...");
    return "default";
}
 
void main() {
    IO.println(Optional.of("cached").orElseGet(this::loadDefault));
    IO.println(Optional.<String>empty().orElseGet(this::loadDefault));
}

Output:

cached
loading default...
default

Notes

The difference from orElse() shows when creating the fallback is expensive or has side effects: orElseGet() calls the function only for an empty Optional.

See also

  • Optional.orElse() — Returns the value, or a fallback if there is none.
  • Supplier — A supplier: a no-argument function that returns a value.

In the tutorial

  • Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.

Thanks for reading!

Donate to the site — we work hard for you.