In the previous tutorials, we discussed how to convert a list to map in Java 8. But when we turn the List to Map, we need to be a bit careful about the entries in the 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 a list like below ways.

Solution 1 :

Java8ListToMap.java
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= deptList.stream()
                .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:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment