Stream ofNullable(T) method in Java with examples
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException.
Syntax:
static <T> Stream<T> ofNullable(T t)
Parameters: This method accepts a single parameter t which is the single element of which the Stream is to be returned.
Return value: This method returns a stream with a single element if the specified element is non-null, otherwise an empty stream.
Below programs illustrate ofNullable(T) method:
Program 1:
// Java program to demonstrate // Stream.ofNullable() method import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a stream with null Stream<String> value = Stream.ofNullable(null); // Print values System.out.println("Values of Stream:"); value.forEach(System.out::println); } } |
The output printed on console of IDE is shown below.
Output:

Program 2:
// Java program to demonstrate // Stream.ofNullable method import java.util.ArrayList; import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create ArrayList containing names ArrayList<String> list = new ArrayList<String>(); list.add("Aman"); list.add("Suraj"); list.add("Zufaq"); // create a stream with ArrayList Stream<ArrayList<String> > value = Stream.ofNullable(list); // print values System.out.println("Values of Stream:"); value.forEach(System.out::println); } } |
The output printed on console is shown below.
Output:

References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#ofNullable(T)
Recommended Posts:
- Stream.max() method in Java with Examples
- Stream min() method in Java with Examples
- Optional stream() method in Java with examples
- Stream forEach() method in Java with examples
- Stream count() method in Java with examples
- Stream generate() method in Java with examples
- OptionalDouble stream() method in Java with examples
- OptionalInt stream() method in Java with examples
- Stream dropWhile() method in Java with examples
- OptionalLong stream() method in Java with examples
- Stream forEachOrdered() method in Java with examples
- Stream skip() method in Java with examples
- BitSet stream() Method in Java with Examples
- Stream noneMatch() method in Java with examples
- Stream takeWhile() method in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



