Handling NullPointerException in Java 8 streams

NullpointerException is every developer’s nightmare. There are high changes that every developer might experience this exception very often than others. There are major cases where this exception brought down entire production environment causing SLA’s to fail.

Streams are major feature in Java but they are more prone to this exception. Let’s see how we can handle streams efficiently. In General, The steam() method is called on the collection of objects, where each object will be passed through a series of operations like filter(), Map(), collect() or forEach() etc.

So, there will be high chance that we run into NullPointerException, since most of the times we don’t know about the data in the underlying collection. For ex. a SQL query returns list of items from database where one or more fields might be null from database.

So in order to avoid those cases we need to be bit cautious while handling streams.

1. One or couple of Objects in the collection are Null

String[] cities = { "Hyderabad", "Delhi", null, "Mumbai", "Fargo", null};

Arrays.asList(cities).stream().filter(Objects::nonNull).forEach(System.out::println);

// output:
Hyderabad
Delhi
Mumbai
Fargo

filter(Objects::nonNull) will not pass any Null objects for further steps i.e forEach()

2. Underlying collection Object itself is Null

String[] cities = { "Hyderabad", "Delhi", null, "Mumbai", "Fargo", null};

List<String> citiesList = Arrays.asList(cities);
Optional.of(citiesList).orElseGet(Collections.emptyList()).stream().filter(Objects::nonNull).forEach(System.out::println);

// output:
Hyderabad
Delhi
Mumbai
Fargo

Lets assign citiesList a Null value

String[] cities = { "Hyderabad", "Delhi", null, "Mumbai", "Fargo", null};

List<String> citiesList = null;
Optional.of(citiesList).orElseGet(Collections.emptyList()).stream().filter(Objects::nonNull).forEach(System.out::println);

// output: 

Since the citiesList is null, the orElseGet(Collections.emptyList()) Method will return an empty list instead of throwing NullPointerException.

This is the foolproof way of handling NullPointerException while working with streams. Above line can be used generically wherever streams being processed.