Java可选为什么不是ifNotPresent方法?

ras*_*cio 5 optional java-8

我想知道为什么在Java8 API上Optional类有方法ifPresent(Consumer< T> consumer)而不是ifNotPresent(Runnable** consumer)

API的目的是什么?是不是模仿功能模式匹配?

**Java没有零参数void功能接口...

Ort*_*kni 9

正如Misha所说,这个功能将以jdk9ifPresentOrElse方式出现.

/**
 * If a value is present, performs the given action with the value,
 * otherwise performs 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 no value is
 *        present
 * @throws NullPointerException if a value is present and the given action
 *         is {@code null}, or no value is present and the given empty-based
 *         action is {@code null}.
 * @since 9
 */
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
    if (value != null) {
        action.accept(value);
    } else {
        emptyAction.run();
    }
}
Run Code Online (Sandbox Code Playgroud)