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

时间:2015-04-02 23:10:07

标签: java-8 optional

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

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

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

1 个答案:

答案 0 :(得分:9)

正如Misha所说,此功能will come with jdk9采用ifPresentOrElse方法的形式。

/**
 * 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();
    }
}