在Java 9中,Optional
Optional.or()方法傳回一個Optional,描述如果存在值則傳回該值,否則傳回由提供函數產生的Optional。
<strong>public Optional<T> or(Supplier<? extends Optional<? extends T><!--? extends Optional<? extends T-->> supplier)</strong>
import java.util.Optional; import java.util.function.Supplier; public class OptionalOrTest { public static void main(String args[]) { <strong>Optional<String></strong> optional = <strong>Optional.of</strong>("TutorialsPoint"); <strong>Supplier<Optional<String>></strong> supplierString = () -> <strong>Optional.of</strong>("Not Present"); optional = <strong>optional.or</strong>(supplierString); optional.<strong>ifPresent</strong>(x -> System.out.println("Value: " + x)); optional = <strong>Optional.empty()</strong>; optional = <strong>optional.or</strong>(supplierString); optional.<strong>ifPresent</strong>(x -> System.out.println("Value: " + x)); } }
<strong>Value: TutorialsPoint Value: Not Present</strong>
以上是Java 9中Optional.or()方法的重要性為何?的詳細內容。更多資訊請關注PHP中文網其他相關文章!