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

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

WBOY
Release: 2023-08-26 13:21:07
forward
1347 people have browsed it

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

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

Output

<strong>TutorialsPoint
1
Tutorix
0</strong>
Copy after login

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

Output

<strong>TutorialsPoint</strong>
Copy after login

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!

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