![]() |
VOOZH | about |
The orElseGet() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method returns the value generated from the specified supplier.
public T orElseGet(Supplier<? extends T> supplier)
Example 1: Using the orElseGet() method with optional chaining.
a
Optional: Optional[9455] Value by orElseGet(Supplier) method: 9455
Explanation: In the above code, we use the Optional and assign the value as 9455 and the supplier is not called. If the supplier generates the random value when optional is empty.
Example 2: Using orElseGet() method with an empty optional.
Optional: Optional.empty Value by orElseGet(Supplier) method: 6
Explanation: In the above code, the optional is empty so when the method calls the supplier generate the the random value because in the supplier we define the Math.random().