What is the Optional.orElseGet method in Java?
In Java, the Optional object is a container object which may or may not contain a value. Using the Optional object’s isPresent method, we can replace the multiple null check. The Optional class is present in the java.util package.
Read more about the
Optionalclass here.
What is the orElseGet method of the Optional class?
The orElseGet method will return the value present in the Optional object.
If the value is not present, then the function passed as an argument is executed and the value returned from the function is returned.
public T orElseGet(Supplier<? extends T> other)
Argument
The argument is the supplier function that is to be executed if the Optional object is empty (if there is no value present in the Optional object).
Return value
If the Optional object contains a value, then the value is returned. Otherwise, the value returned from the passed argument function is returned.
This method throws
NullPointerExceptionif no value is present and the supplier function isnull.
Code
The below code denotes how to use the orElseGet method.
import java.util.Optional;class OptionalOrElseGetExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);Integer val = optional1.orElseGet(()-> 10);System.out.println("Value at Optional1 is : " + val);Optional<Integer> optional2 = Optional.empty();System.out.println("\nOptional2 : " + optional2);val = optional2.orElseGet(()-> 10);System.out.println("Value at Optional2 is : " + val);}}
Explanation
In the above code:
- In line number 1, we import the
Optionalclass.
import java.util.Optional;
- In line number 5, we create an
Optionalobject of theIntegertype with value1using theofmethod.
Optional<Integer> optional1 = Optional.of(1);
- In line number 7, we call the
orElseGemethod on theoptional1object. For theorElseGetmethod, a function which returns10is passed as an argument. This method returns1because theoptional1object contains the value.
Integer val = optional1.orElseGet(()-> 10);
val;// 1
- In line number 10, we use the
emptymethod to get an emptyOptionalobject of theIntegertype. The returned object doesn’t have any value.
Optional<Integer> optional2 = Optional.empty();
- In line number 12, we call the
orElseGemethod on theoptional2object. For theorElseGetmethod, a function which returns10is passed as an argument. This method returns10because theoptional2object doesn’t contain any value.
val = optional2.orElseGet(()-> 10);
val;// 10