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

Reviewed-by: dfuchs, lowasser
This commit is contained in:
Paul Sandoz 2015-02-13 11:13:27 +01:00
parent 3cb54779b0
commit 4b2af9acf9
8 changed files with 413 additions and 80 deletions

View file

@ -38,8 +38,8 @@ import java.util.stream.Stream;
* <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 @@ public final class Optional<T> {
}
/**
* 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();
}
}