Using Optional containers for primitive number types

Download java eBook

Example

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();

Stats

Contributors: 4
2016-12-30
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook