Avoid NullPointerException in Java 9 with Stream.ofNullable

Last Updated on


This post demonstrates how to avoid NullPointerException in Java 9 when working with Stream and using the overloaded of  method.

The Problem

The java.util.stream.Stream interface has these 2 methods:

Passing a null array reference

In this example, a null is passed to the a non-null-safe overloaded method that takes an array of generic values.

These codes throw an NullPointerException:

Passing a null reference

In the examples below, we can pass a null reference. BUT when a chained method is invoked that accepts Lambda expressions and processes the reference, it blow up with NullPointerException.

Consider these codes:

This results to:

Another example:

This results to similar output:

Using Stream.ofNullable

This new method returns an empty stream is the passed reference is null.

This outputs: 0


Karl San Gabriel

Professional Software Developer