Monday , December 11 2017
Home / java8 / Resolve NullPointerException in Collectors.toMap

Resolve NullPointerException in Collectors.toMap

In the previous example we have discussed how to convert the 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 the list contains any null values, the toMap() method will throw NullPointerException in Collectors.toMap.

NullPointerException in Collectors.toMap ?

To convert 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 your 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= 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 chandrashekhar

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+ ,

Recommended

Java 8 how to remove duplicates from list

In this tutorials, I am going to show you how to remove duplicate elements from …

Leave a Reply

Your email address will not be published. Required fields are marked *