Relates :
|
Optional is a useful abstraction as a Container for values that may or may not exist. It is increasingly used to enforce additional rigor with null handling as such there are a couple of common usage patterns: 1) performing computation on an Optional value if present, otherwise obtain a default. Optional<T> optional; // ... Value v = optional.isPresent() ? someFunction(optional.get()) : defaultSupplier(); 2) perform some computation on an Optional value, if present, or throw an exception Value v; if (optional.isPresent()) { v = someFunction(optional.get()); } else { throw new SomeException(); } given the existence of lambdas and some other similar patterns expressed as lambda processing methods (e.g: the family of compute... methods on Map) Optional could benefit from the addition of: public <V> V computeIfPresentOrElseGet(Function<T, V> mappingFunction, Supplier<V> defaultSupplier); public <V> V computeIfPresentOrElseThrow(Function<T, V> mappingFunction, Supplier<? extends Throwable> exceptionSupplier);