OptionalDouble orElseGet() method in Java with examples

The orElseGet(java.util.function.DoubleSupplier) method helps us to get the value in this OptionalDouble object. If a value is not present in this OptionalDouble, then this method returns the result produced by the supplying function, passed as the parameterÂ
Syntax:
public double orElseGet(DoubleSupplier supplier)
Parameters: This method accepts the supplying function that produces a value to be returned.Â
Return value: This method returns the double value, if present, otherwise the result produced by the supplying function.Â
Exception: This method throw NullPointerException if no value is present and the supplying function is null.Â
Below programs illustrate orElseGet(java.util.function.DoubleSupplier) method:Â
Program 1:Â
Java
// Java program to demonstrate// OptionalDouble.orElseGet(DoubleSupplier) methodÂ
import java.util.OptionalDouble;Â
public class GFG {Â
    public static void main(String[] args)    {Â
        // create a OptionalDouble        OptionalDouble opdouble = OptionalDouble.of(2134);Â
        // get value using orElseGet        double value = opdouble.orElseGet(() -> getdoubleValue());Â
        // print double value        System.out.println("value: " + value);    }Â
    public static double getdoubleValue()    {        return 3242 + 123;    }} |
Output:
value: 2134.0
Program 2:Â
Java
// Java program to demonstrate// OptionalDouble.orElseGet(DoubleSupplier) methodÂ
import java.util.OptionalDouble;Â
public class GFG {Â
    public static void main(String[] args)    {Â
        // create a OptionalDouble        OptionalDouble opdouble = OptionalDouble.empty();Â
        // get value using orElseGet        double value = opdouble.orElseGet(() -> getdoubleValue());Â
        // print double value        System.out.println("value: " + value);    }Â
    public static double getdoubleValue()    {        return 3242 * 234;    }} |
Output:
value: 758628.0



