Convert Stream to Map using collect(toMap())
Stream collect(toMap())
toMap() method returns a Collector that accumulates elements into a Map.
Convert stream to Map – collect(toMap())
Stream’s collect(toMap()) gathers a stream elements into a key-value collection.
Here is an example:
public class Employee { private int id; private String name; public Employee(int id, String name) { this.id = id; this.name = name; } public String getName() { return name; } public int getId() { return id; } public String toString() { return "Name: '" + getName() + "', Id: '" + getId() + "'"; } }
package com.topjavatutorial.java8examples; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.topjavatutorial.Employee; public class StreamOperations { public static void main(String[] args) { Employee emp1 = new Employee(1,"Ajay"); Employee emp2 = new Employee(2,"Bob"); Employee emp3 = new Employee(3,"Chetan"); List<Employee> empList = new ArrayList<Employee>(); empList.add(emp1); empList.add(emp2); empList.add(emp3); Map<Integer,String> collectedMap = empList.stream() .collect(Collectors.toMap(Employee::getId,Employee::getName)); collectedMap.forEach((k,v) -> System.out.println("Key : " + k + " , Value : " + v)); } }
Output:
Key : 1 , Value : Ajay
Key : 2 , Value : Bob
Key : 3 , Value : Chetan
When we want to get a mapping of Employee Ids to the employee objects, we could use an utility method Function.identity() :
package com.topjavatutorial.java8examples; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import com.topjavatutorial.Employee; public class StreamOperations { public static void main(String[] args) { Employee emp1 = new Employee(1,"Ajay"); Employee emp2 = new Employee(2,"Bob"); Employee emp3 = new Employee(3,"Chetan"); List<Employee> empList = new ArrayList<Employee>(); empList.add(emp1); empList.add(emp2); empList.add(emp3); Map<Integer,Employee> collectedMap = empList.stream() .collect(Collectors.toMap(Employee::getId,Function.identity())); collectedMap.forEach((k,v) -> System.out.println("Key [ " + k + "] , Value : [" + v + "]")); } }
Output :
Key [ 1] , Value : [Name: ‘Ajay’, Id: ‘1’]
Key [ 2] , Value : [Name: ‘Bob’, Id: ‘2’]
Key [ 3] , Value : [Name: ‘Chetan’, Id: ‘3’]
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post