Home  >  Java 8

Java 8 Convert List to Map using Collectors.toMap() Example

By Arvind Rai, September 24, 2016
On this page we will provide java 8 convert List to Map using Collectors.toMap() example. Using lambda expression, we can convert List to Map in a single line. Java 8 provides Collectors.toMap() that is useful to convert List to Map. We need to pass mapping function for key and value. To avoid conflict of duplicate keys, we pass merge function otherwise it will throw IllegalStateException. By default Collectors.toMap() returns HashMap and if we want to change it we need to pass required supplier instance. Now find the toMap() method syntax.

toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)

The arguments are as follows.

Function keyMapper: It generates key for Map.

Function valueMapper: It generates value for Map.

BinaryOperator mergeFunction: This is optional. The usability of merge function is to handle the situation of duplicate Map keys. Using BinaryOperator we can merge the values of duplicate keys. If we do not pass this argument, then by default it throws IllegalStateException in case of duplicate keys.

Supplier mapSupplier: This is optional. It returns a Map in which data is filled as key/value. If we do not pass map supplier then the default supplier will return HashMap. If we want to get any other instance such as LinkedHashMap, we need to pass supplier as LinkedHashMap::new.

List to Map with Key Mapper and Value Mapper

Here we will pass mapping function of key mapper and value mapper. The syntax of method is as follows. toMap(Function keyMapper, Function valueMapper) Now find a simple example.
ListToMap1.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ListToMap1 {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("Mohan");
		list.add("Sohan");
		list.add("Mahesh");
		Map<String, Object> map = list.stream().collect(Collectors.toMap(Function.identity(), s->s));
		map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y));
	}
} 
Output
Key: Mohan, value: Mohan
Key: Mahesh, value: Mahesh
Key: Sohan, value: Sohan 
Now we have a List of user class Person. Find the code to convert the list into map.
ListToMap2.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMap2 {
	public static void main(String[] args) {
		List<Person> list = new ArrayList<>();
		list.add(new Person(100, "Mohan"));
		list.add(new Person(200, "Sohan"));
		list.add(new Person(300, "Mahesh"));
		Map<Integer, String> map = list.stream()
				.collect(Collectors.toMap(Person::getId, Person::getName));
		map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y));
	}
} 
Person.java
package com.concretepage;
public class Person {
	private Integer id;
	private String name;
	public Person(Integer id, String name) {
		this.id = id;
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
} 
Output
Key: 100, value: Mohan
Key: 200, value: Sohan
Key: 300, value: Mahesh 
Here if keys will be duplicate then, it will throw IllegalStateException. To solve it, we pass merge function as BinaryOperator.

List to Map with Key Mapper, Value Mapper and Merge Function

In this example we will pass BinaryOperator as merge function. When the toMap() method finds duplicate keys then the values are merged and it does not throw exception. Find the method syntax.
toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)
Find the example.
ListToMapWithBinaryOperator.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapWithBinaryOperator {
	public static void main(String[] args) {
		List<Person> list = new ArrayList<>();
		list.add(new Person(100, "Mohan"));
		list.add(new Person(100, "Sohan"));
		list.add(new Person(300, "Mahesh"));
		Map<Integer, String> map = list.stream()
				.collect(Collectors.toMap(Person::getId, Person::getName, (x, y) -> x+", "+ y));
		map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y));
	}
} 
Output
Key: 100, value: Mohan, Sohan
Key: 300, value: Mahesh 

List to Map with Key Mapper, Value Mapper, Merge Function and Map Supplier

Here we will pass map supplier in the toMap() method. If we want to return LinkedHashMap, we need to pass supplier as LinkedHashMap::new.
toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)
Find the example.
ListToMapWithSupplier.java
package com.concretepage;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
public class ListToMapWithSupplier {
	public static void main(String[] args) {
		List<Person> list = new ArrayList<>();
		list.add(new Person(100, "Mohan"));
		list.add(new Person(100, "Sohan"));
		list.add(new Person(300, "Mahesh"));
		LinkedHashMap<Integer, String> map = list.stream()
				.collect(Collectors.toMap(Person::getId, Person::getName, 
						(x, y) -> x+", "+ y, LinkedHashMap::new));
		map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y));
	}
} 
Output
Key: 100, value: Mohan, Sohan
Key: 300, value: Mahesh 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us