What is the OptionalInt.orElseGet method in Java?
The orElseGet method will return the integer value present in the OptionalInt object. If the value is not present, then the IntSupplier function passed as an argument is executed, and the integer value returned from the function is returned.
In Java, the
OptionalIntobject is a container object that may or may not contain anintegervalue.
The
OptionalIntclass is present in thejava.utilpackage.
Syntax
public int orElseGet(IntSupplier other)
Parameters
The argument is that the IntSupplier function is to be executed if the OptionalInt object is OptionalInt object
Return value
If the OptionalInt 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 theIntSupplierfunction isnull.
Code
The code below shows how to use the orElseGet method.
import java.util.OptionalInt;class OptionalIntOrElseGetExample {public static void main(String[] args) {OptionalInt optional1 = OptionalInt.of(1);System.out.println("Optional1 : " + optional1);int val = optional1.orElseGet(()-> 10);System.out.println("Int Value at Optional1 is : " + val);OptionalInt optional2 = OptionalInt.empty();System.out.println("\nOptional2 : " + optional2);val = optional2.orElseGet(()-> 10);System.out.println("Int Value at Optional2 is : " + val);}}
Explanation
In the code above:
- In line 1, we imported the
OptionalIntclass.
import java.util.OptionalInt;
- In line 5, we created an
OptionalIntobject withintvalue1using theofmethod.
OptionalInt optional1 = OptionalInt.of(1);
- In line 7, we called the
orElseGetmethod on theoptional1object. For theorElseGetmethod, a function that returns10is passed as an argument. TheorElseGetmethod returns1because theoptional1object contains the value.
int val = optional1.orElseGet(()->10);
val;// 1
- In line 10, we used the
emptymethod to get an emptyOptionalIntobject. The returned object doesn’t have any value.
OptionalInt optional2 = OptionalInt.empty();
- In line 12, we called the
orElseGetmethod 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