What is the OptionalLong.orElse method in Java?
Overview
In Java, the OptionalLong object is a container object which may or may not contain a long value.
The OptionalLong class is present in the java.util package.
The orElse() method
The orElse method will return the long value present in the OptionalLong object. If the value is not present, then the passed argument is returned.
Syntax
public long orElse(long other)
Argument
The argument is the long value to be returned if the OptionalLong object is empty, which means there is no value present in the OptionalLong object.
Return value
If the OptionalLong object contains a long value, then the value is returned. Otherwise, the passed argument is returned.
Code
The code below denotes how to use the orElse method.
import java.util.OptionalLong;class OptionalLongOrElseExample {public static void main(String[] args) {OptionalLong optional1 = OptionalLong.of(1);System.out.println("Optional1 : " + optional1);System.out.println("Long Value at Optional1 is : " + optional1.orElse(10));OptionalLong optional2 = OptionalLong.empty();System.out.println("\nOptional2 : " + optional2);System.out.println("Long value at Optional2 is : " + optional2.orElse(3223232323l));}}
Explanation
In the code above:
-
Line 1: We imported the
OptionalLongclass.
import java.util.OptionalLong;
-
Line 5: We created an
OptionalLongobject with the value1using theofmethod.
OptionalLong optional1 = OptionalLong.of(1);
-
Line 7: We called the
orElsemethod on theoptional1object with10as an argument. This method returns1because theoptional1object contains the value.
optional1.orElse(10); // 1
-
Line 9: We used the
emptymethod to get an emptyOptionalLongobject. The returned object doesn’t have any value.
OptionalLong optional2 = OptionalLong.empty();
-
Line 11: We called the
orElsemethod on theoptional2object with3223232323las an argument. This method returns3223232323because theoptional2object doesn’t contain any value.
optional2.orElse(3223232323l); //3223232323