在Java 9版本中,引入了Optional.ifPresentOrElse()和Optional.or()方法來改進其功能。 Optional.ifPresentOrElse()方法檢查值是否存在,如果存在則應用具有值的操作,否則返回空操作,而Optional.or()方法檢查值是否存在,如果存在則傳回包含值的選項,否則傳回應用於Supplier函數的Optional。 Optional.ifPresentOrElse()方法包含兩個參數,Consumer和Runnable,而Optional.or()方法只包含一個參數,Supplier。
<strong>public void ifPresentOrElse(Consumer<? super T><!--? super T--> action, Runnable emptyAction)</strong>
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() { <strong>Optional<String></strong> optional = <strong>Optional.of</strong>("Test"); AtomicInteger successCounter = new AtomicInteger(); AtomicInteger emptyOptionalsCounter = new AtomicInteger(); optional.<strong>ifPresentOrElse</strong>(x -> successCounter.incrementAndGet(), () -> emptyOptionalsCounter.incrementAndGet()); System.out.println(successCounter.get()); System.out.println(emptyOptionalsCounter.get()); } private static void optionalIsEmpty() { Optional optional = <strong>Optional.empty()</strong>; AtomicInteger successCounter = new AtomicInteger(); AtomicInteger emptyOptionalsCounter = new AtomicInteger(); optional.<strong>ifPresentOrElse</strong>(x -> successCounter.incrementAndGet(), () -> emptyOptionalsCounter.incrementAndGet()); System.out.println(successCounter.get()); System.out.println(emptyOptionalsCounter.get()) } }
<strong>1 0 0 1</strong>
<strong>public Optional<T> or(Supplier<? extends Optional<? extends T<!--? extends Optional<? extends T-->>> supplier)</strong>
import java.util.Optional; public class OptionalOrMethodTest { public static void main(String args[]) { optionalIsPresent(); optionalIsEmpty(); } private static void optionalIsPresent() { <strong>Optional<String></strong> optional1 = <strong>Optional.of</strong>("Test1"); <strong>Optional<String></strong> optional2 = <strong>Optional.of</strong>("Test2"); <strong>Optional<String</strong><strong>></strong> optional3 = <strong>optional1.or</strong>(() -> optional2); System.out.println(optional3.get()); } private static void optionalIsEmpty() { <strong>Optional<String></strong> optional1 = <strong>Optional.empty()</strong>; <strong>Optional<String></strong> optional2 = <strong>Optional.of</strong>("Test2"); <strong>Optional<String></strong> optional3 = <strong>optional1.or</strong>(() -> optional2); System.out.println(optional3.get()); } }
<strong>Test1 Test2</strong>
以上是Java 9中Optional.ifPresentOrElse()和Optional.or()方法之間的差異是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!