JDK-8331875 : Enhance the utility of java.util.Optional with additional lambdas
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • Submitted: 2024-05-07
  • Updated: 2024-05-10
Related Reports
Relates :  
Description
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);