Friday , October 20 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) {
        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;

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 =
                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

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


Java 8 Read File Line By Line Example

In this tutorials, I am going to show you how to read a File line …

Leave a Reply

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