The orElseGet() method of the Optional class returns the value stored in the Optional when it is present. When the Optional is empty, it obtains a replacement value from the specified Supplier.
- The Supplier generates the alternative value only when the Optional is empty.
- orElseGet() is useful when the default value requires computation or method execution.
- A NullPointerException occurs when the Optional is empty and the supplied Supplier is null.
Syntax
public T orElseGet(Supplier<? extends T> supplier)
- Parameters: supplier generates the value returned when the Optional is empty.
- Return Value: The method returns the value stored in the Optional. If no value is present, it returns the value generated by the Supplier.
- Exception: NullPointerException is thrown when the Optional is empty and the specified Supplier is null.
Examples of orElseGet() Method
The following examples demonstrate how orElseGet() behaves when the Optional contains a value and when it is empty.
1. Using orElseGet() With a Present Value
The following program uses orElseGet() with an Optional containing the value 9455. A Supplier is also provided to generate a random value when required.
import java.util.*;
import java.util.function.*;
public class Geeks {
public static void main(String[] args)
{
Optional<Integer> op = Optional.of(9455);
System.out.println("Optional: " + op);
System.out.println("Value by orElseGet(Supplier) method: "+ op.orElseGet(() -> (int)(Math.random() * 10)));
}
}
Output
Optional: Optional[9455] Value by orElseGet(Supplier) method: 9455
Explanation: The Optional contains 9455, so orElseGet() returns the existing value. The Supplier is not executed because a value is already present.
2. Using orElseGet() With an Empty Optional
The following program uses an empty Optional. A Supplier is provided to generate a random value if the Optional is empty.
import java.util.*;
import java.util.function.*;
public class Geeks {
public static void main(String[] args) {
Optional<Integer> op = Optional.empty();
System.out.println("Optional: " + op);
System.out.println("Value by orElseGet(Supplier) method: "
+ op.orElseGet(
() -> (int) (Math.random() * 10)
));
}
}
Output
Optional: Optional.empty Value by orElseGet(Supplier) method: 2
Explanation: The Optional is empty, so orElseGet() executes the Supplier. Math.random() generates a value, which is returned as the default result.
Note: The random output may differ each time the program runs.