Java 8 List to Map duplicate keys

Today, I introduce you to 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.


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.


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


c) Here is the demo program


That’s all about the Java 8 List to Map duplicate keys. You may be interested in Java 8 Stream Distinct Examples.

Java 8 Collectors JavaDoc

Download the complete source code, click link below (341 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons