List to Map using Stream and Collectors in Java

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);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pratiyush Prakash

Pratiyush Prakash

Full stack dev @ Texas Instruments. Follow me for short articles on software development. I will cover topics like Spring boot, Angular, SQL and so on.