--- old/src/java.base/share/classes/java/util/Optional.java 2015-02-12 18:48:47.000000000 +0100 +++ new/src/java.base/share/classes/java/util/Optional.java 2015-02-12 18:48:47.000000000 +0100 @@ -38,8 +38,8 @@ *
Additional methods that depend on the presence or absence of a contained * value are provided, such as {@link #orElse(java.lang.Object) orElse()} * (return a default value if value not present) and - * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block - * of code if the value is present). + * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (perform an + * action if the value is present). * *
This is a value-based * class; use of identity-sensitive operations (including reference equality @@ -148,16 +148,35 @@ } /** - * If a value is present, invoke the specified consumer with the value, + * If a value is present, perform the given action with the value, * otherwise do nothing. * - * @param consumer block to be executed if a value is present - * @throws NullPointerException if value is present and {@code consumer} is + * @param action the action to be performed if a value is present + * @throws NullPointerException if a value is present and {@code action} is * null */ - public void ifPresent(Consumer super T> consumer) { + public void ifPresent(Consumer super T> action) { if (value != null) { - consumer.accept(value); + action.accept(value); + } + } + + /** + * 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(); } }