Home> Java> javaTutorial> body text

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

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

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

ofNullable()method is a static method of theStreamclass. If it is not empty, it returns a sequential Stream containing a single element. , otherwise it returns empty.Java 9This method was introduced to avoidNullPointerExceptionsand avoidnull checksfor streams. The main goal of using theofNullable()method is to return annull optionwhen the value is null.

Syntax H2>
static  Stream ofNullable(T t)
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.ofNullable(5000).count(); System.out.println(count); System.out.println("Tutorix"); count = (int) Stream.ofNullable(null).count(); System.out.println(count); } }
Copy after login

Output

TutorialsPoint 1 Tutorix 0
Copy after login

Example 2

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

Output

TutorialsPoint
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
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!