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.
staticStream ofNullable(T t)
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); } }
TutorialsPoint 1 Tutorix 0
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 } }
TutorialsPoint
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!