使用可選容器表示原始數字型別
OptionalDouble
, OptionalInt
和 OptionalLong
的工作方式與 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();