Java 8 List to Map duplicate keys

Today, I introduce you about Java 8 List to Map duplicate keys examples. Here, we will use Collectors.toMap() method to convert a List of an object into a Map. One more thing, If List has duplicates but Map doesn’t allow duplicate keys. When you are converting List to Map and what will happen?

Let’s discovery via the examples below:

1. Java 8 List to Map – Collectors.toMap()

We’re considering a list of the People objects, and uses Collectors.toMap to convert it into a Map.

Output

2. Java 8 List to Map duplicate keys

a) In case there are more than one objects which are duplicated key. If we try to convert them to map, a duplicated key errors will be thrown. Let’s see detail the program below.

Output

Java 8 List to Map duplicate keys

b) Fix the duplicated key issue

To solve the duplicated key issue above, pass in the third mergeFunction argument such as

Or

c) Here is the demo program

Output

That’s all about the Java 8 List to Map duplicate keys.

References
Java 8 Collectors JavaDoc

Download the complete source code, click link below

ListToMapExample.zip (3 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons