Java 8 NullPointerException in Collectors.toMap

The Java 8 Collectors.toMap throws a NullPointerException if one of the values is ‘null’. This error make developers confused and don’t know why this behavior happens, although maps can contain null pointers as value without any problems. Is there a good reason why values cannot be null for Collectors.toMap?

Let’s check the example to see this error happens, we have a java program like this:

Run the above java program, getting the exception

Actually, this error comes from a Open JDK known bug, but we can work around it with some ways:

Using method putAll() of HashMap:

Using forEach:

Both of ways, a map will contains null value, like this:

If you want to filter out null value, using this:

and the map result don’t contain null value any more:

So depends on your cases and choose the right way. That’s it.

Leave a Comment

Please share it if you found this useful
Hide Buttons