在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中文网其他相关文章!