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.
Syntax of orElseGet() Method
public T orElseGet(Supplier<? extends T> supplier)
- Parameters: It takes a parameter supplier of type T to generate a value to return if there is no value present in this Optional instance.
- Return Type: It returns a 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.
- Exception: if the value is not present and the supplied function is null, then it throws a NullPointerException.
Example 1: Using the orElseGet() method with optional chaining.
// Java program to demonstrate
// Optional.orElseGet() method
import java.util.*;
import java.util.function.*;
public class Geeks
{
public static void main(String[] args)
{
// create a Optional
Optional<Integer> op
= Optional.of(9455);
// print supplier
System.out.println("Optional: "
+ op);
// orElseGet supplier
System.out.println("Value by orElseGet"
+ "(Supplier) method: "
+ op.orElseGet(
() -> (int)(Math.random() * 10)));
}
}
a
Output
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.
// Java program to demonstrate
// Optional.orElseGet() method
import java.util.*;
import java.util.function.*;
public class Geeks
{
public static void main(String[] args)
{
// create a Optional
Optional<Integer> op
= Optional.empty();
// print supplier
System.out.println("Optional: "
+ op);
try {
// orElseGet supplier
System.out.println("Value by orElseGet"
+ "(Supplier) method: "
+ op.orElseGet(
() -> (int)(Math.random() * 10)));
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
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().