Java 8: convert List into Map
Suppose we have a List
of objects and want to convert into Map
.
Before Java 8 we can just iterate over List
and populate key and value:
List persons = Arrays.asList("Bob", "Natalie", "Alice");
final Map<String, Integer> map = new HashMap<>();
for (final String person : persons) {
map.put(person, person.length());
}
With java 8 we can use Collectors.toMap()
method to do the conversion.
List persons = Arrays.asList("Bob", "Natalie", "Alice");
Map<String, Integer> map = persons.stream()
.collect(Collectors.toMap(person -> person, String::length));
System.out.println(map);
//output
{Bob=3, Natalie=7, Alice=5}
While creating map we need to provide two functions for map’s key and value.
What if we add a duplicate key in map. Exception will be thrown:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 6
at java.util.stream.Collectors.lambda$throwingMerger$114(Collectors.java:133)
For solving this there is a overload method of Collectors.toMap()
3rd parameter of it is the merge function. For instance we can use in the following way:
List persons = Arrays.asList("Bob", "Natali", "Alice", "Tom"); Map<Integer, String> map = persons.stream().collect(Collectors.toMap( String::length, person -> person, (s1, s2) -> s1 + "," + s2)); System.out.println(map); //output {6=Natali, 3=Bob,Tom, 5=Alice} [addToAppearHere]
Map implementation is not guaranteed, it can be anything. But there is an another overloaded method where we can specify desired implementation. If we want sorted map we can use TreeMap
following way:
List persons = Arrays.asList("Bob", "Natali", "Alice", "Tom");
Map<Integer, String> map = persons.stream().collect(Collectors.toMap(
String::length, person -> person, (s1, s2) -> s1 + "," + s2, TreeMap::new));
System.out.println(map);
//output
{3=Bob,Tom, 5=Alice, 6=Natali}