Java 8 Convert List to Map using Streams API
7 years ago Lalit Bhagtani 1
Java 8 Convert List to Map :- In this tutorial, we will learn to convert list to map using Stream API.
Note :- To keep this tutorial short and concise, Employee Bean used in the example is not given here, you can check it here.
Problem Statement :-
Given a list of Employee object convert it to the map, containing employee id as a Key and employee designation as a Value.
Let’s see the implementation of above problem in java 7 and in java 8.
Java 7 :- To implement this, iterate through the list of Employee object and add employee id as a Key and employee designation as a Value to the map.
public static void main(String[] args){ List<Employee> empList = new ArrayList<Employee>(); empList.add(new Employee(1,"Robert","Manager")); empList.add(new Employee(2,"Martin","General Manager")); empList.add(new Employee(3,"Jack","Manager")); Map<Long,String> map = new HashMap<Long,String>(); for(Employee emp : empList){ map.put(emp.getEmpId(),emp.getDesignation()); } Entry<Long,String> entry = null; Set<Entry<Long,String>> set = map.entrySet(); Iterator<Entry<Long,String>> iterate = set.iterator(); while(iterate.hasNext()){ entry = iterate.next(); System.out.println("Key : "+entry.getKey() + " , Value : "+entry.getValue()); } }
Java 8 :- To implement this, we will use Collectors.toMap() method of Stream API.
public static void main(String[] args){ List<Employee> empList = new ArrayList<Employee>(); empList.add(new Employee(1,"Robert","Manager")); empList.add(new Employee(2,"Martin","General Manager")); empList.add(new Employee(3,"Jack","Manager")); Map<Long,String> map = empList.stream() .collect(Collectors.toMap(Employee::getEmpId,Employee::getDesignation)); map.forEach((k,v) -> System.out.println("Key : "+ k + " , Value : "+ v )); }
Result :-
Key : 1 , Value : Manager
Key : 2 , Value : General Manager
Key : 3 , Value : Manager
Reference :- Collectors JavaDocs
That’s all for Java 8 Convert List to Map. If you liked it, please share your thoughts in comments section and share it with others too.
1 thought on “Java 8 Convert List to Map using Streams API”
we have map() method what is the use for this, is it like MAP or other