How to convert List to Map in Java 8 using Stream API?
UPDATED: 15 June 2015
Tags:
Collectors
,
List
,
Map
,
Stream
Code snippet demonstrate converting List<T> to Map<K,V>.
Source code(User.java)
Source code(ExampleListToMap.java)
Output
Source code(User.java)
public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Source code(ExampleListToMap.java)
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javaQuery.beans.User; public class ExampleListToMap { public static void main(String[] args) { /* Creating List<String> */ List<String> listStrings = new ArrayList<String>(); listStrings.add("Vicky"); listStrings.add("Thakor"); /** * Convert List<String> to Map<String, String> using `stream` API * Explanation: * Collectors.toMap(String::toString, listStringName -> listStringName) * - String::toString => Calling `toString()` method of `String` class. * (Note: Its compulsory to set `key` of Map from String class.) * * - listStringName -> listStringName => Value of Map. */ Map<String, String> mapName = listStrings.stream() .collect(Collectors.toMap(String::toString, listStringName -> listStringName)); /* Print the Map */ System.out.println("List<String> to Map<String, String>: " + mapName); System.out.println("+++++++++++++++++++++++++++++++++++++++++++"); /* Creating User objects */ User objUser = new User(); objUser.setId(1L); objUser.setName("Vicky Thakor"); User objUser2 = new User(); objUser2.setId(2L); objUser2.setName("Chirag Thakor"); /* Add users to List<User> */ List<User> listUsers = new ArrayList<User>(); listUsers.add(objUser); listUsers.add(objUser2); /** * Convert List<User> to Map<Long, User> using `stream` API. * Explanation: * Collectors.toMap(User::getId, user -> user) * - User::getId => Calling `getter` method of `User` class. * (Note: Its compulsory to set `key` of Map from User class.) * * - user -> user => Value of Map. */ Map<Long, User> mapUsers = listUsers.stream().collect(Collectors.toMap(User::getId, user -> user)); /* Print the Map */ System.out.println("List<User> to Map<Long, User>:"); mapUsers.keySet() .forEach(key -> { User getUser = mapUsers.get(key); System.out.println(key + "=" + getUser.getName()); }); } }
Output
List<String> to Map<String, String>: {Vicky=Vicky, Thakor=Thakor} +++++++++++++++++++++++++++++++++++++++++++ List<User> to Map<Long, User>: 1=Vicky Thakor 2=Chirag Thakor
Tags:
Collectors
,
List
,
Map
,
Stream
0 comments :