$show=/label

Java 8 - Convert List to Map (Handling Duplicate Keys)

SHARE:

A quick example to understand how to convert List to Map in Java 8 and exploring the different ways to do.

Convert List to Map in Java

1. Introduction


In this article, You'll explore and learn how to convert List to Map in Java 8. 

First, Let us convert List into Map.
Next, Convert List of user-defined(custom) objects to Map and handling with the duplicate keys.
Finally, Sort and collect the Map from List

Java 8 - Convert List to Map (Handling Duplicate Keys)


2. Collectors.toMap() Method: List<V> into Map<K, V>


Collectors is a new Java 8 utility class that provides many methods to collect the output of stream into final List or Set or Map.

Collectors.toMap() method is a overloaded method takes 2, 3, and 4 arguments in 3 forms.

Syntax:


public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper,
                                                    BinaryOperator<U> mergeFunction)

public static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper,
                                                                Function<? super T,? extends U> valueMapper,
                                                                BinaryOperator<U> mergeFunction,
                                                                Supplier<M> mapSupplier)



This method is used to take the keyMapper and valueMapper Function functional interface and returns Collector object which holds our new output Map.

toMap() is to convert the given function mappers into a new Map.


3. Java 8 List To Map: Collectors.toMap()


The below program to work with the simple Strings objects to convert List to Map.

package Collectors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8ListToMapExample {

public static void main(String[] args) {

List<String> names = new ArrayList<String>();

names.add("james");
names.add("Cisran");
names.add("Paul");

System.out.println("names list values are : " + names);

// Names length map
Map<String, Integer> namesLengthMap = names.stream().collect(Collectors.toMap(String::new, String::length));

System.out.println("names length map : ;" + namesLengthMap);
// Nanmes to upper case
Map<String, String> namesUppercaseMap = names.stream().collect(Collectors.toMap(String::new, String::toUpperCase));

System.out.println("names upper case map : ;" + namesUppercaseMap);
}

}
Output:

names list values are : [james, Cisran, Paul]
names length map : ;{Cisran=6, james=5, Paul=4}
names upper case map : ;{Cisran=CISRAN, james=JAMES, Paul=PAUL}

4. Java 8 List<V> into Map<K, V> with Custom Objects


Creating an Employee class with id, name, salary, age, location along with constructor, setters & getter methods. This class will be used throughout this article.
class Employee {

	private int id;
	private String name;
	private long salary;
	private int age;
	private String location;
	
	public Employee(int id, String name, long salary, int age, String location) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
		this.age = age;
		this.location = location;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getSalary() {
		return salary;
	}
	public void setSalary(long salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
}

Converting List<Employee> into various Map combinations.

package Collectors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8ListToMapExample {

	public static void main(String[] args) {

		List<Employee> names = new ArrayList<Employee>();

		names.add(new Employee(100, "James", 1000, 35, "USA"));
		names.add(new Employee(101, "Cisran", 5000, 25, "UK"));
		names.add(new Employee(102, "Paul", 7000, 40, "AUS"));

		System.out.println("Employees list values are : " + names);

		// Map - Id, Name
		Map<Integer, String> idNameMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getName));

		System.out.println("Map <Id, Name>" + idNameMap);

		// Map - Id, Salary
		Map<Integer, Long> idSalaryMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getSalary));

		System.out.println("Map <Id, Salary>" + idSalaryMap);

		// Map - Id, Age
		Map<Integer, Integer> idAgeMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getAge));

		System.out.println("Map <Id, Age>" + idAgeMap);

		// Map - Id, Location
		Map<Integer, String> idLocationMap = names.stream()
				.collect(Collectors.toMap(Employee::getId, Employee::getLocation));

		System.out.println("Map <Id, Location>" + idLocationMap);

	}

}
Output:

Employees list values are : [Collectors.Employee@60f82f98, Collectors.Employee@35f983a6, Collectors.Employee@7f690630]
Map <Id, Name>{100=James, 101=Cisran, 102=Paul}
Map <Id, Salary>{100=1000, 101=5000, 102=7000}
Map <Id, Age>{100=35, 101=25, 102=40}
Map <Id, Location>{100=USA, 101=UK, 102=AUS}

5. Java 8 List<V> into Map<K, V> with Custom Duplicate Objects Objects - MergerFunction


Now let us add the new employee with id 102 which already exists in the list.

names.add(new Employee(102, "Gena", 3000, 30, "NZ"));

Next, Run the full code as below. toMap() method, we are passing getId() as the key that means id should be unique in the list but it has duplicates for id 102. We should see the runtime exception now.

package Collectors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8ListToMapExample {

	public static void main(String[] args) {

		List<Employee> names = new ArrayList<Employee>();

		names.add(new Employee(100, "James", 1000, 35, "USA"));
		names.add(new Employee(101, "Cisran", 5000, 25, "UK"));
		names.add(new Employee(102, "Paul", 7000, 40, "AUS"));

		names.add(new Employee(102, "Gena", 3000, 30, "NZ"));

		// Map - Id, Name
		Map<Integer, String> idNameMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getName));

		System.out.println("Map <Id, Name>" + idNameMap);

	}

}

Output:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key Paul
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1254)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at Collectors.Java8ListToMapExample.main(Java8ListToMapExample.java:21)


Error is completely misleading as it is showing the Name instead of duplicate id 102.

In this case, if you know which one to ignore then we are good to use the toMap() overloaded method with mergeFunction.

Please use the below syntax and provide custom mergeFunction logic to ignore the duplicate one.


public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper,
                                                    BinaryOperator<U> mergeFunction)


BinaryOperator functional interface takes the same type as input and returns the same type as output. This is a subinterface to BiFunction and takes two parameters.

public class Java8ListToMapExample {

	public static void main(String[] args) {

		List<Employee> names = new ArrayList<Employee>();

		names.add(new Employee(100, "James", 1000, 35, "USA"));
		names.add(new Employee(101, "Cisran", 5000, 25, "UK"));
		names.add(new Employee(102, "Paul", 7000, 40, "AUS"));

		names.add(new Employee(102, "Gena", 3000, 30, "NZ"));

		// Map - Id, Name
		Map<Integer, String> idNameMap = names.stream()
				.collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> newValue));

		System.out.println("Map <Id, Name>" + idNameMap);

	}

}
Output:

Map <Id, Name>{100=James, 101=Cisran, 102=Gena}
Name for id 102 is replaced with the new value.

Try with old value: This ignores the next duplicate occurrence.

Map<Integer, String> idNameMap = names.stream()
   .collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> oldValue));
Output:

Map <Id, Name>{100=James, 101=Cisran, 102=Paul}

6. Convert List to LinkedHashMap and TreeMap (Sort) with Collectors.toMap() - Supplier


As of now, we've seen how to convert List to Map and default output of key-value pair is stored into HashMap.

toMap() has another overloaded method that takes 4th argument Supplier. From the Supplier, You need to pass the LinkedHashMap or TreeMap object as shown in the below example.

package Collectors;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Java8ListToMapExample {

	public static void main(String[] args) {

		List<Employee> names = new ArrayList<Employee>();

		names.add(new Employee(100, "James", 1000, 35, "USA"));
		names.add(new Employee(101, "Cisran", 5000, 25, "UK"));
		names.add(new Employee(102, "Paul", 7000, 40, "AUS"));

		names.add(new Employee(102, "Gena", 3000, 30, "NZ"));

		// Map - Id, Name
		LinkedHashMap<Integer, String> linkedhashMap = names.stream().collect(Collectors.toMap(Employee::getId,
				Employee::getName, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

		System.out.println("LinkedHashMap <Id, Name>" + linkedhashMap);

		// Map - Id, Name
		TreeMap<String, String> treeMap = names.stream().collect(Collectors.toMap(Employee::getName,
				Employee::getLocation, (oldValue, newValue) -> oldValue, TreeMap::new));

		System.out.println("TreeMap <Id, Name>" + treeMap);

	}

}
Output:

LinkedHashMap <Id, Name>{100=James, 101=Cisran, 102=Paul}
TreeMap <Id, Name>{Cisran=UK, Gena=NZ, James=USA, Paul=AUS}

From the output, First LinkedHashMap stored 3 key-value pairs whereas TreeMap has 4 key-value pairs because the key is an emp name which is not having the duplicates names.

7. Conclusion


In this article, You've seen in-depth about how to convert List to Map in Java 8. How to deal with Custom objects in List and convert them into Map.

How to handle the duplicate custom objects if List is having?

By default, toMap() method converts List into HashMap but there are some cases you may encounter to convert to LinkedHashMap or TreeMap. To convert to your own map, you need to provide the Supplier to toMap() function.

As usual, All examples are shown over the GitHub.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,14,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,72,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,10,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - Convert List to Map (Handling Duplicate Keys)
Java 8 - Convert List to Map (Handling Duplicate Keys)
A quick example to understand how to convert List to Map in Java 8 and exploring the different ways to do.
https://1.bp.blogspot.com/-Aa8nLjpE8ns/XxvqiFBp-SI/AAAAAAAAC20/8_xVvByt0asv4RiXPWtMD7pKAeyPU3sewCLcBGAsYHQ/w400-h211/Java%2B8%2B-%2BConvert%2BList%2Bto%2BMap%2B%2528Handling%2BDuplicate%2BKeys%2529.png
https://1.bp.blogspot.com/-Aa8nLjpE8ns/XxvqiFBp-SI/AAAAAAAAC20/8_xVvByt0asv4RiXPWtMD7pKAeyPU3sewCLcBGAsYHQ/s72-w400-c-h211/Java%2B8%2B-%2BConvert%2BList%2Bto%2BMap%2B%2528Handling%2BDuplicate%2BKeys%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/07/java-8-convert-list-to-map-handling-duplicate-keys.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/07/java-8-convert-list-to-map-handling-duplicate-keys.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content