Java 9 中 Optional.ifPresentOrElse() 和 Optional.or() 方法之间的差异?
**Optional.ifPresentOrElse()** 和 **Optional.or()** 这两个方法都在 Java 9 版本中引入,以改善其功能。**Optional.ifPresentOrElse()** 方法检查值是否存在,如果有则使用该值执行操作,否则返回空操作;而 **Optional.or()** 方法检查值是否存在,如果有,则返回包含该值的选项,否则返回应用于 Supplier 函数的 Option。**Optional.ifPresentOrElse()** 方法包含两个参数,**Consumer **和 **Runnable **;而 **Optional.or()** 方法仅包含一个参数,**Supplier**。
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
广告