Java Language Using Optional containers for primitive number types

Download Java Language for free


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.

// Gives the other value as the original Optional is empty.
int finalValue = absentInt.orElseGet(this::otherValue);

// Will throw a NoSuchElementException.
int nonexistentValue = absentInt.getAsInt();
Oracle Official Code Standard