Java, Software Development

Avoid NullPointerException with Stream.ofNullable in Java 9

We can now avoid the NullPointerException in Java with Stream.ofNullable! This post demonstrates how to avoid NullPointerException when working with Java Stream API in Java 9.

Java 8 – The Problem With Stream.of Methods

The Stream interface has the following two methods in Java 8. The problem with these methods is that they throw exceptions when they argument are null or contain null values.

Consider the following sample codes.

Passing A null Array Reference

When we pass null to a non-null-safe overloaded method that takes an array, the codes throw a NullPointerException.

The codes generate the following output.

Passing A null Reference

In the examples below, we can pass an array that has a null reference element. The array has two elements – “a” and null. When the codes process that null element, the codes throw a NullPointerException. Consider the following codes.

This results in:

Consider another example.

This results in a similar output:

In Java 8, the only way to avoid the NullPointerException is by using if statements to check for null values.

Avoid NullPointerException With Java 9 Stream.ofNullable

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

This outputs: 0

As easy as that! We can now avoid NullPointerException with Stream.ofNullable when using Java Stream API in Java 9.

Although the Java Stream API is powerful, it is generally to keep its usage to a minimum. Codebase with a lot of Lamda expressions is large to analyze because of poor readability. On the other hand, when we use Java Stream API we need to be aware that they are not bullet-proof and they can throw NullPointerException. Now, a couple NullPointerException with too many hard-to-read Lambda expressions, our codes will be hard to maintain. Using Stream.ofNullable can ease the pain but it is just a nice-to-have feature in real-life application codes.

So the takeaways are – avoid the Java Stream API as much as possible, and, if we cannot, make sure we are using the Stream.ofNullable method or use if statements for checking for null values.

This post is (now) part of a reboot Java tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like