OptionalDouble
, OptionalInt
and OptionalLong
work like Optional
, but are specifically designed to wrap primitive types:
OptionalInt presentInt = OptionalInt.of(value);
OptionalInt absentInt = OptionalInt.empty();
Because numeric types do have a value, there is no special handling for null. Empty containers can be checked with:
presentInt.isPresent(); // Is true.
absentInt.isPresent(); // Is false.
Similarly, shorthands exist to aid value management:
// Prints the value since it is provided on creation.
presentInt.ifPresent(System.out::println);
// Gives the other value as the original Optional is empty.
int finalValue = absentInt.orElseGet(this::otherValue);
// Will throw a NoSuchElementException.
int nonexistentValue = absentInt.getAsInt();