Thursday, 14 July 2016

Convert List into Map in Java 8

Convert List<V> into Map<K, V> in Java 8

Sometimes it is necessary to convert a List of Objects to Map in Java 8.
In Java 8 we can simply do this using Collectors class .
Let us look at the following example.

class Employee {
 public String name;
 public int age;

 Employee(String name, int age) { = name;
  this.age = age;

 public String getName() {
  return name;

Now we can convert a list of Employee Objects to a Map like this
We will use the names of the Employees as the key of the Map.

List<Employee> empList = Arrays.asList(
                            new Employee("Jim", 18),
                            new Employee("Joe", 25), 
                            new Employee("Harry", 40)
Map<String, Employee> result =
                    .collect(Collectors.toMap(Employee::getName, x -> x));



Joe   =, 
Harry =, 
Jim   =

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.