Java 9中Optional.ifPresentOrElse()和Optional.or()方法之间的区别?
无论Optional.ifPresentOrElse()和Optional.or()方法在Java的版本9中引入了以改善其功能。该Optional.ifPresentOrElse()方法检查值存在,适用行动值,否则返回空的动作,而Optional.or()方法检查值存在,返回选项包含的值,否则返回可选适用于供应商功能可按。Optional.ifPresentOrElse()方法包含两个参数,消费者 和可运行 而Optional.or()方法仅包含一个参数,供应商。
Optional.ifPresentOrElse()的语法:
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
Optional.or()的语法:
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