How to handle NullPointerException in Collectors.toMap when a mapped value is null

less than 1 minute read

In Java 8, Collectors.toMap throws NullPointerException when one of the mapped value is null. This is a known bug in OpenJDK. There are many workaround to handle this.

The Problem

The problem statement is simple, I have a list of Employee, given that employee’s salary can be null, I want to map of salary by employeeId.

When we run this code, we get a null pointer exception.

Solution - Using Custom Collector

We are going to create a custom collector, if you have no idea how to create one, follow this post

So here is our modified code, we have just replaced Collectors implementation with CustomCollector.

We have fixed the issue with Collectors.toMap with our custom implementation.

Categories: ,


Kumar Rohit

Kumar Rohit

I like long drives, bike trip & good food. I have passion for coding, especially for Clean-Code.

Leave a comment