Home > Java > javaTutorial > body text

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

王林
Release: 2023-08-22 15:57:02
forward
1033 people have browsed it

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

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

Optional 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>
Copy after login

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));
   }
}
Copy after login

Output

<strong>Value: TutorialsPoint
Value: Not Present</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!