What is the OptionalDouble.orElseGet method in Java?

In Java, the OptionalDouble object is a container object that may or may not contain a double value.

The OptionalDouble class is present in the java.util package.

The orElseGet method will return the double value present in the OptionalDouble object. If the value is not present then the DoubleSupplier function passed as an argument is executed and the double value from the function is returned.

public double orElseGet(DoubleSupplier other)

Argument

The argument in the DoubleSupplier function is to be executed if the OptionalDouble object is empty (no value is present in the OptionalDouble object).

Return value

If the OptionalDouble object contains a value, then the value is returned. Otherwise, the value from the passed argument function is returned.

This method throws NullPointerException if no value is present, or DoubleSupplier function if null.

Code

The code below denotes how to use the orElseGet method.

import java.util.OptionalDouble;
class OptionalDoubleOrElseGetExample {
public static void main(String[] args) {
OptionalDouble optional1 = OptionalDouble.of(1.5);
System.out.println("Optional1 : " + optional1);
double val = optional1.orElseGet(()-> 111.11);
System.out.println("Double Value at Optional1 is : " + val);
OptionalDouble optional2 = OptionalDouble.empty();
System.out.println("\nOptional2 : " + optional2);
val = optional2.orElseGet(()-> 111.11);
System.out.println("Double Value at Optional2 is : " + val);
}
}

Explanation

In the code above:

  • In line 1, we imported the OptionalDouble class.

  • In line 5, we created an OptionalDouble object with a double value of 1.5 using the of method.

  • In line 7, we called the orElseGet method on the optional1 object. For the orElseGet method a function which returns 111.11 is passed as an argument. The orElseGet method returns 1.5 because the optional1 object contains the value.

  • In line 10, we used the empty method to get an empty OptionalDouble object. The returned object doesn’t have any value.

  • In line 12, we called the orElseGet method on the optional2 object. For the orElseGet method, a function that returns 111.11 is passed as an argument. This method returns 111.11 because the optional2 object doesn’t contain a value.

Free Resources