使用可选容器表示原始数字类型

OptionalDoubleOptionalIntOptionalLong工作方式Optional类似,但它们专门用于包装原始类型:

OptionalInt presentInt = OptionalInt.of(value);
OptionalInt absentInt = OptionalInt.empty();

因为数字类型确实有值,所以对 null 没有特殊处理。可以使用以下方法检查空容器:

presentInt.isPresent(); // Is true.
absentInt.isPresent(); // Is false.

同样,存在缩写来帮助价值管理:

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