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