Java对原始数字类型使用可选容器
示例
OptionalDouble,OptionalInt和OptionalLong工作一样Optional,但专为包装基本类型:
OptionalInt presentInt = OptionalInt.of(value); OptionalInt absentInt = OptionalInt.empty();
由于数字类型确实具有值,因此没有对null的特殊处理。可用以下方法检查空容器:
presentInt.isPresent(); //是真的。 absentInt.isPresent(); //是假的。
同样,也存在一些有助于价值管理的捷径:
//打印值,因为它是在创建时提供的。 presentInt.ifPresent(System.out::println); //给出另一个值,因为原始的Optional为空。 int finalValue = absentInt.orElseGet(this::otherValue); //将抛出NoSuchElementException。 int nonexistentValue = absentInt.getAsInt();