List to Map using Stream and Collectors in Java

Pratiyush Prakash
1 min readDec 27, 2021

Problem statement

You have a list of Employee objects and you have to create a map of email and Employee object.

public class Employee {
private String firstName,
private String lastName,
private Double salary,
private String email,
private Integer departmentId,
.
.
.
Constructor, Getters and Setters
}

Solution

First of all, you might be wondering what is the benefit of saving the employee list as map, right?

The answer is time complexity, in case of Employee list it would take us O(n) to find an employee while with Map it would take us O(1).

Okay, so coming to the solution. There is obviously a trivial way of doing this using for loop, I will not be covering that. Let’s jump right into the quicker way of doing the same.

List<Employee> list; // This list is given to youMap<String, Employee> map = list.stream().collect(Collectors.toMap(Employee::email, employee -> employee);// as we are using the stream, so if you want to filter your list, you can even do that.// let's take one example. We want to create a valid map, so we will filter out only those employees which doesn't have email as null.Map<String, Employee> map = list.stream().filter(employee -> null != employee.getEmail()).collect(Collectors.toMap(Employee::email, employee -> employee);

--

--

Pratiyush Prakash

Full stack Dev and Lead @ Texas Instruments. Follow me for short articles on software development.