无论Optional.ifPresentOrElse()和Optional.or()方法在Java的版本9中引入了以改善其功能。该Optional.ifPresentOrElse()方法检查值存在,适用行动值,否则返回空的动作,而Optional.or()方法检查值存在,返回选项包含的值,否则返回可选适用于供应商功能可按。 Optional.ifPresentOrElse()方法包含两个参数,消费者 和可运行 而Optional.or()方法仅包含一个参数,供应商。
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; public class IfPresentOrElseMethodTest { public static void main(String args[]) { optionalIsPresent(); optionalIsEmpty(); } private static void optionalIsPresent() { Optional<String> optional = Optional.of("Test"); AtomicInteger successCounter = new AtomicInteger(); AtomicInteger emptyOptionalsCounter = new AtomicInteger(); optional.ifPresentOrElse(x -> successCounter.incrementAndGet(), () -> emptyOptionalsCounter.incrementAndGet()); System.out.println(successCounter.get()); System.out.println(emptyOptionalsCounter.get()); } private static void optionalIsEmpty() { Optional optional = Optional.empty(); AtomicInteger successCounter = new AtomicInteger(); AtomicInteger emptyOptionalsCounter = new AtomicInteger(); optional.ifPresentOrElse(x -> successCounter.incrementAndGet(), () -> emptyOptionalsCounter.incrementAndGet()); System.out.println(successCounter.get()); System.out.println(emptyOptionalsCounter.get()) } }
输出结果
1 0 0 1
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
import java.util.Optional; public class OptionalOrMethodTest { public static void main(String args[]) { optionalIsPresent(); optionalIsEmpty(); } private static void optionalIsPresent() { Optional<String> optional1 = Optional.of("Test1"); Optional<String> optional2 = Optional.of("Test2"); Optional<String> optional3 = optional1.or(() -> optional2); System.out.println(optional3.get()); } private static void optionalIsEmpty() { Optional<String> optional1 = Optional.empty(); Optional<String> optional2 = Optional.of("Test2"); Optional<String> optional3 = optional1.or(() -> optional2); System.out.println(optional3.get()); } }
输出结果
Test1 Test2