Monday , December 11 2017
Home / java8 / How to convert List to Map in Java 8

How to convert List to Map in Java 8

In this tutorials, we are going to learn how to convert List to Map in Java 8.

Convert List to Map in Java 8 :

We can convert the Java List<?> of objects into Map<k,v> in Java 8 via the Collectors class. The Collectors class provides a toMap() method to convert List to Map.

Collectors.toMap() :

toMap() is a static method. It returns the Collector instance containing results (Map) of provided mapping functions as input parameters.

To convert the List to Map in Java 8, the list should initially convert to Stream and then only we can convert it as Map.

Example List to Map in Java 8 :

class Department {
    private int deptId;
    private String deptName;

    public Department(int deptId, String deptName) {
        super();
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public int getDeptId() {
        return deptId;
    }
    public String getDeptName() {
        return deptName;
    }

}

Convert List To Map :

Here we are going to convert a list of Department objects in to Map.

package com.onlinetutorialspoint.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8_ListToMap {

    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, "Management"));
        deptList.add(new Department(4, "Development"));
        deptList.add(new Department(5, "Recruitment"));
        Map<Integer, String> deptMap = deptList.stream().collect(
                Collectors.toMap(Department::getDeptId, Department::getDeptName));
        
        deptMap.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v));
    }
    
}

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

On the above example runs well if the map doesn’t contain any null key or values. If any one of the entry null the toMap() method throws NullPointerException.


        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 = deptList.stream().collect(
                Collectors.toMap(Department::getDeptId, Department::getDeptName));
        
        deptMap.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v));

The above code will generate NullPointerException like below:

Exception in thread “main” java.lang.NullPointerException
at java.util.stream.Collectors.lambda$toMap$58(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)

You can see how to resolve NullPointerException in Collectors.toMap() here.

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 *