Optional类中ifPresentOrElse()方法的改进是接受两个参数Consumer和Runnable。使用ifPresentOrElse()方法的目的是,如果Optional包含一个值,则会对所包含的值(即action.accept(value))调用函数action ,这与ifPresent()方法一致。与ifPresent()方法的区别在于ifPresentOrElse()具有第二个参数emptyAction。如果Optional不包含任何值,则ifPresentOrElse()方法将调用emptyAction,即emptyAction.run()。
语法public void ifPresentOrElse(Consumer super T> action, Runnable emptyAction)
示例import java.util.Optional;
public class IfPresentOrElseMethodTest {
public static void main(String args[]) { Optional optional = Optional.of(1);
optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
System.out.println("Not Present"));
optional = Optional.empty();
optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
System.out.println("Not Present"));
}
}
输出结果Value: 1
Not Present