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) {
  this.name = 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 = empList.stream()
                    .collect(Collectors.toMap(Employee::getName, x -> x));

System.out.println(result);


Output:

{
Joe   = codermag.net.java8.Employee@404b9385, 
Harry = codermag.net.java8.Employee@6d311334, 
Jim   = codermag.net.java8.Employee@682a0b20
}