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
Optional
class here.
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)
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).
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
NullPointerException
if no value is present and the supplier function isnull
.
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);}}
In the above code:
Optional
class.import java.util.Optional;
Optional
object of the Integer
type with value 1
using the of
method.Optional<Integer> optional1 = Optional.of(1);
orElseGe
method on the optional1
object. For the orElseGet
method, a function which returns 10
is passed as an argument. This method returns 1
because the optional1
object contains the value.Integer val = optional1.orElseGet(()-> 10);
val;// 1
empty
method to get an empty Optional
object of the Integer
type. The returned object doesn’t have any value.Optional<Integer> optional2 = Optional.empty();
orElseGe
method on the optional2
object. For the orElseGet
method, a function which returns 10
is passed as an argument. This method returns 10
because the optional2
object doesn’t contain any value.val = optional2.orElseGet(()-> 10);
val;// 10