Java Optional orElseGet() Method
Example
Get the name, or a default value from a lambda expression:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();
System.out.println(name.orElseGet(() -> "Guest"));
System.out.println(noName.orElseGet(() -> "Guest"));
}
}
Definition and Usage
The orElseGet() method returns the value in the Optional. If the Optional is empty, it runs a lambda expression (a short block of code that works like a method) and returns its result.
It works like orElse(), but the default value is only created when the Optional is empty. This is useful when the default value takes work to create.
Syntax
public T orElseGet(Supplier<? extends T> other)
T refers to the data type of the value in the Optional.
Parameter Values
| Parameter | Description |
|---|---|
| other | Required. A Supplier object or lambda expression with no parameters, that returns the default value. |
Technical Details
| Returns: | The value if there is one, otherwise the result of other. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods