--- a/jdk/src/java.base/share/classes/java/util/Optional.java Fri Feb 13 11:03:57 2015 +0800
+++ b/jdk/src/java.base/share/classes/java/util/Optional.java Fri Feb 13 11:13:27 2015 +0100
@@ -38,8 +38,8 @@
* <p>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).
*
* <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
* 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();
}
}