In Java, an OptionalLong
object is a container object that may or may not contain a long
value.
The
OptionalLong
class is present in thejava.util
package.
The getAsLong()
method is used to get the long
value present in an OptionalLong
object. If the OptionalLong
object doesn’t have a value, then NoSuchElementException
is thrown.
public long getAsLong()
This method doesn’t take any argument.
The code below shows how to use the getAsLong()
method.
import java.util.OptionalLong;class OptionalLongGetExample {public static void main(String[] args) {OptionalLong optional = OptionalLong.of(1);System.out.println("Value present in the optional object is: " + optional.getAsLong());}}
In the code above:
OptionalLong
class.import java.util.OptionalLong;
of()
method to get an OptionalLong
object with value 1
.OptionalLong optional = OptionalLong.of(1);
getAsLong()
method on the object optional
. The getAsLong()
method will return the value present in optional
.optional.getAsLong(); // 1