Resolve NullPointerException in Collectors.toMap

By |2018-03-30T19:37:52+05:30November 30th, 2017|java8|

In the previous tutorials, we discussed about how to convert a list to map in Java 8. But when we convert the List to Map we need to be a bit careful about the entries in map.

If a list contains null values, the toMap() method will throw NullPointerException in Collectors.toMap.

Why NullPointerException in Collectors.toMap ?

While converting the list to map, the toMap() method internally uses merge() method from java.util.Map interface. The merge() is a default method which was introduced in Java 8. It doesn’t allow the null key or values.

Java Doc Says : The merge() will throw NullPointerException – the specified key is null and this map does not support null keys or the value or remappingFunction is null.

How to resolve NullPointerException in Collectors.toMap ?

We can avoid the NullPointerException by using the foreach method of list like below ways.

Solution 1 :

​package com.onlinetutorialspoint.java8;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Java8ListToMap {
    public static void main(String[] args) {
        List<Department> deptList = new ArrayList<Department>();   
        deptList.add(new Department(1, "IT"));
        deptList.add(new Department(2, "HR"));
        deptList.add(new Department(3, null));
        deptList.add(new Department(4, "Development"));
        deptList.add(new Department(5, "Recruitment"));
        Map<Integer,  String> deptMap = new HashMap<>();
        deptList.forEach((dept) -> deptMap.put(dept.getDeptId(), dept.getDeptName()));
        deptMap.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v));


Output :

​DeptId (1) Name :IT
DeptId (2) Name :HR
DeptId (3) Name :null
DeptId (4) Name :Development
DeptId (5) Name :Recruitment​

Solution 2 :

​Map<Integer, String> map=
                .collect(HashMap::new, (m,v)->m.put(v.getDeptId(), v.getDeptName()), HashMap::putAll);
        map.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v));​

Output :

​DeptId (1) Name :IT
DeptId (2) Name :HR
DeptId (3) Name :null
DeptId (4) Name :Development
DeptId (5) Name :Recruitment

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment