How to Convert List to Map in Java 8 | Java 8 Examples | Java Inspires



 Hi Guys, 

Welcome to Java Inspires..

In this post, we will see how to convert List into Map using Collectors.map in Java 8.

Here, we will create an employee list then we will convert the list to map.


Java8Example.java

package com.javainspires.java8example;

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

/**
 * 
 * @author Java Inspires
 *
 */
public class Java8Example {

	public static void main(String[] args) {
		// create employee objects
		Employee emp1 = new Employee(101L, "Mark", 28);
		Employee emp2 = new Employee(102L, "Musk", 35);
		Employee emp3 = new Employee(103L, "Gates", 45);
		// add employee objects to list
		List<Employee> empList = new ArrayList<Employee>();
		empList.add(emp1);
		empList.add(emp2);
		empList.add(emp3);
		// print list of employees
		System.out.println("List of Employees");
		System.out.println(empList);
		System.out.println();

		// convert list to map using stream collect
		Map<Long, Employee> empMap = empList.stream()
				.collect(Collectors.toMap(Employee::getEmpId, Function.identity()));
		// print employee map
		System.out.println("Employee Map");
		System.out.println(empMap);
		System.out.println();

		// print key values from map
		System.out.println("Key = Value");
		empMap.entrySet().stream().forEach(e -> {
			System.out.println(e.getKey() + " = " + e.getValue());
		});

	}
}

class Employee {
	private Long empId;
	private String empName;
	private Integer empAge;

	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Employee(Long empId, String empName, Integer empAge) {
		super();
		this.empId = empId;
		this.empName = empName;
		this.empAge = empAge;
	}

	public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public Integer getEmpAge() {
		return empAge;
	}

	public void setEmpAge(Integer empAge) {
		this.empAge = empAge;
	}

}

Run the above java class:
Output:
List of Employees
[com.javainspires.java8example.Employee@15db9742, com.javainspires.java8example.Employee@6d06d69c, com.javainspires.java8example.Employee@7852e922]

Employee Map
{101=com.javainspires.java8example.Employee@15db9742, 102=com.javainspires.java8example.Employee@6d06d69c, 103=com.javainspires.java8example.Employee@7852e922}

Key = Value
101 = com.javainspires.java8example.Employee@15db9742
102 = com.javainspires.java8example.Employee@6d06d69c
103 = com.javainspires.java8example.Employee@7852e922

Thank You 


Post a Comment

Previous Post Next Post