Home  >  Article  >  Java  >  When to use ofNullable() method of Stream in Java 9?

When to use ofNullable() method of Stream in Java 9?

WBOY
WBOYforward
2023-08-26 13:21:071317browse

在Java 9中什么时候使用Stream的ofNullable()方法?

ofNullable() method is a static method of the Stream class. If it is not empty, it returns a sequential Stream containing a single element. , otherwise it returns empty. Java 9 This method was introduced to avoid NullPointerExceptions and avoid null checks for streams. The main goal of using the ofNullable() method is to return an null option when the value is null.

Syntax H2>
<strong>static <T> Stream<T> ofNullable(T t)</strong>

Example 1

import java.util.stream.Stream;
public class OfNullableMethodTest1 {
   public static void main(String args[]) {
      System.out.println("TutorialsPoint");
      int count = (int) Stream.<strong>ofNullable</strong>(5000).count();
      System.out.println(count);
      System.out.println("Tutorix");
      count = (int) Stream.<strong>ofNullable</strong>(null).count();
      System.out.println(count);
   }
}

Output

<strong>TutorialsPoint
1
Tutorix
0</strong>

Example 2

import java.util.stream.Stream;
public class OfNullableMethodTest2 {
   public static void main(String args[]) {
      String str = null;
      Stream.<strong>ofNullable</strong>(str).forEach(System.out::println); <strong>// prints nothing in the console</strong>
      str = "TutorialsPoint";
      Stream.<strong>ofNullable</strong>(str).forEach(System.out::println); <strong>// prints TutorialsPoint</strong>
   }
}

Output

<strong>TutorialsPoint</strong>

The above is the detailed content of When to use ofNullable() method of Stream 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