RFR 8071670: java.util.Optional: please add a way to specify if-else behavior

Paul Sandoz paul.sandoz at oracle.com
Tue Feb 3 15:38:50 UTC 2015


Hi,

http://cr.openjdk.java.net/~psandoz/jdk9/JDK-8071670-Optional-ifPresentOrElse/webrev/

Here is another tweak to Optional (and primitives) that has some weight:

/**
 * If a value is present, perform the given action with the value,
 * otherwise perform the given empty-based action.
 *
 * @param action the action to be performed if a value is present
 * @param emptyAction the empty-based action to be performed if a value is
 * not present
 * @throws NullPointerException if a value is present and {@code action} is
 * null, or a value is not present and {@code emptyAction} is null.
 * @since 1.9
 */
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
    if (value != null) {
        action.accept(value);
    } else {
        emptyAction.run();
    }
}

(In hindsight we should have been consistent and thrown NPEs regardless of the optional state. The exception throwing behaviour is consistent with ifPresent.)

Previously it was kind of awkward if one had two lambdas or method refs handy, one had to do:

  o.ifPresent(v -> ...);
  if (!o.ifPresent()) {
    ...
  }

Or just:

  if (o.ifPresent()) {
    ...
  } else {
     ... 
  }


I also updated the language of the ifPresent methods to be more consistent with Collection/Stream.forEach.

Paul.



More information about the core-libs-dev mailing list