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

JavaObject Oriented ProgrammingProgramming

The ofNullable() method is a static method of Stream class that returns a sequential Stream containing a single element if non-null, otherwise returns an empty. Java 9 has introduced this method to avoid NullPointerExceptions and also avoid null checks of streams. The main objective of using the ofNullable() method is to return an empty option if the value is null.

Syntax

static <T> Stream<T> ofNullable(T t)

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);
   }
}

Output

TutorialsPoint
1
Tutorix
0

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
   }
}

Output

TutorialsPoint
raja
Published on 19-Feb-2020 10:43:19
Advertisements