Other classes similar to OptionalInt
are OptionalDouble
, OptionalLong
, and Optional
.
These help us eliminate exceptions that occur due to the absence of a value at runtime.
The key is to first check if the Optional contains a value before trying to retrieve it.
Table of Content
Java OptionalInt example
OptionalInt
allows us to create an object which may or may not contain an int value.
If a value is present, isPresent()
will return true and getAsInt()
will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse()
.
OptionalIntExample
In this example, we return an OptionalInt
from a Stream created from an integer array and finally return a value using the reduce()
method.
If the value is present, then only we print it using getAsInt()
.
package javaexp.blogspot.stream;
import java.util.Arrays;
import java.util.OptionalInt;
public class OptionalIntExample {
public static void main(String[] args) {
int iarray[] = {9, 10, 11, 12, 15, 15, 25};
OptionalInt result = Arrays.stream(iarray)
.reduce((left, right) -> left);
if (result.isPresent()) {
System.out.println("First element of Array: " + result.getAsInt());
}
}
}
Summary
OptionalInt
and other respective Optional classes help protect against
NullPointerException
when trying to retrieve values from potentially null objects.
They provide a safer way to work with values that may or may not be present.