Stream ofNullable method in Java

1. Introduction

The signature of the method is:

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

This method produces a sequential Stream comprising one element if it’s not null; otherwise, returns an empty Stream. This method is helpful in dealing with null values in the stream. The main advantage of this method is that can avoid NullPointerException and null checks everywhere.

2. Example

Let us understand this with the help of an example.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OfNullableExample {
    public static void main(String[] args) {
        List<String> l = new ArrayList<String>();
        System.out.println("Original list: " + l);

        // filter not null values using null check
        List<String> l2 = l.stream().filter(o -> o != null).collect(Collectors.toList());
        System.out.println("Filtered values using null check: " + l2);

        // filter not null values using flatMap and ofNullable
        List<String> l3 = l.stream().flatMap(o->Stream.ofNullable(o)).collect(Collectors.toList());
        System.out.println("Filtered values using flatMap and ofNullable: " + l3);


3. Conclusion

In conclusion, the Stream.ofNullable() method in Java offers a convenient way to handle null values when working with streams. Stream.ofNullable() enhances the readability and robustness of Java code when dealing with potential null values in stream contexts.