How to Convert List into Map Using Java 8 ?

In this article we will see how to convert List into Map using Java 8 ? While working with Java applications you might come up with a situation where you want to convert List into Map.

Here in our example, we will convert List<Employee> to Map<Long, Employee>.
Below is Employee Class.

public class Employee {

	private long empId;

	private String name;

	private String cmpName;

	public Employee(long empId, String name, String cmpName) {
		this.empId = empId;
		this.name = name;
		this.cmpName = cmpName;
	}
	
	public Employee() {
		
	}

	public long getEmpId() {
		return empId;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCmpName() {
		return cmpName;
	}

	public void setCmpName(String cmpName) {
		this.cmpName = cmpName;
	}

}

Now lets convert List into Map using Java 8 Stream API.

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

import com.example.pojo.Employee;

public class ListToMap {

	public static void main(String[] args) {
		
		List<Employee> list = new ArrayList<Employee>();
		
		list.add(new Employee(1, "Raj", "Tata"));
		list.add(new Employee(2, "John", "Infosys"));
		
		Map<Long, Employee> map = list.stream()
		.collect(Collectors.toMap(Employee :: getEmpId, employee -> employee));
		
		System.out.println(map.get(1L).getName());
		
	}

}

0 Comments