Home  >  Article  >  Java  >  What is the importance of Optional.or() method in Java 9?

What is the importance of Optional.or() method in Java 9?

王林
王林forward
2023-08-22 15:57:021006browse

Java 9中Optional.or()方法的重要性是什么?

##In Java 9, some static methods have been added to the

Optional8742468051c85b06f0a0af9e3e506b5c class: stream(), or()andifPresentOrElse(). The introduction of the Optional class solves the null pointer exception problem. The

Optional.or() method returns an Optional describing a value that is returned if present, otherwise an Optional generated by the provided function.

Syntax

<strong>public Optional<T> or(Supplier<? extends Optional<? extends T><!--? extends Optional<? extends T-->> supplier)</strong>

Example

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));
   }
}

Output

<strong>Value: TutorialsPoint
Value: Not Present</strong>

The above is the detailed content of What is the importance of Optional.or() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete