This is possible using the mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction):

Map<String, String> phoneBook = 
    people.stream()
          .collect(Collectors.toMap(
             Person::getName,
             Person::getAddress,
             (address1, address2) -> {
                 System.out.println("duplicate key found!");
                 return address1;
             }
          ));

mergeFunction is a function that operates on two values associated with the same key. adress1 corresponds to the first address that was encountered when collecting elements and adress2 corresponds to the second address encountered: this lambda just tells to keep the first address and ignores the second.

Answer from Tunaki on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ java map โ€บ handle duplicate keys when producing map using java stream
Handle Duplicate Keys When Producing Map Using Java Stream | Baeldung
January 8, 2024 - Furthermore, the toMap() method allows us to specify a merge function that will be used to combine values associated with duplicate keys. For example, we can use a simple lambda expression to ignore the latter City objects if their names have ...
Discussions

java - handle duplicate key in Collectors.toMap() function - Stack Overflow
See also How to get the key in Collectors.toMap merge function? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Improve Collectors.toMap(Function,Function) error message for duplicate keys
GWT version: 2.8.0 Browser (with version): Chrome 56.0.2924.87 (64-bit) Operating System: Windows 7 Description Improve Lambda error messages. Please execute the example i've attached. What i g... More on github.com
๐ŸŒ github.com
6
March 8, 2017
Java 8 -> Collectors.toMap -> Duplicate key - Stack Overflow
I m trying to convert List of available Currency to a Map, To look up based on Currency Numeric code i want to get String code. Here is the code. But this code above throwing below error, I m very... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Duplicate key (attempted merging values x and x) - Stack Overflow
Map map = ruleList.stream().collect(Collectors.toMap(Rule::getId, Rule::getCableType)); The list has a duplication like (1, 10), (1,40) and when I'm running this code I get this exception: Exception in thread "main" java.lang.IllegalStateException: Duplicate key 21 (attempted ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Javadevcentral
javadevcentral.com โ€บ collectors tomap duplicate key
Collectors toMap Duplicate Key | Java Developer Central
December 2, 2019 - In this case, when the stream pipeline encounters a duplicate key, it will call the merge function with both the values i.e., the value already mapped to the current (duplicate) key and the new value (result of the value mapper function for ...
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-collectors-tomap-method-explained-f95999d4ebe6
Javaโ€™s Collectors.toMap() Method Explained | Medium
October 20, 2024 - By default, if two elements share the same key, toMap() does not know how to resolve the conflict, and it results in an error. Letโ€™s look at an example that demonstrates this behavior.
๐ŸŒ
GitHub
github.com โ€บ gwtproject โ€บ gwt โ€บ issues โ€บ 9495
Improve Collectors.toMap(Function,Function) error message for duplicate keys ยท Issue #9495 ยท gwtproject/gwt
March 8, 2017 - Exception in thread "main" java.lang.IllegalStateException: Duplicate key Item [id=1, name=1-Test] at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133) at java.util.HashMap.merge(HashMap.java:1253) at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320) The code works fine, i only want highlight that the error message in Pure Java is way better than i GWT.
Author ย  mseele
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ collectors-tomap-method-in-java-with-examples
Collectors toMap() method in Java with Examples - GeeksforGeeks
December 26, 2025 - Collectors.toMap(p -> p[0], p -> p[1]) maps the first element as the key and the second element as the value. Handle duplicate keys in the stream. Collectors.toMap(Function keyMapper, Function valueMapper, BinaryOperator<U> mergeFunction) ...
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ java 8 โ€บ java collectors.tomap(): collecting stream items into map
Java Collectors.toMap(): Collecting Stream Items into Map
October 14, 2023 - Map<Long, Item> map = stream.collect(Collectors.toMap(Item::id, Function.identity())); // {1=Item[id=1, name=Item1], 2=Item[id=2, name=Item2], 3=Item[id=3, name=Item3]} If the stream has items where Map keys are duplicates, there are two possible ways to handle it:
๐ŸŒ
DevGenius
blog.devgenius.io โ€บ you-should-be-aware-of-this-if-you-are-using-collectors-tomap-in-java-5d2e7bbd136
You Should Be Aware of This if You Are Using Collectors.toMap in Java | by Pratiyush Prakash | Dev Genius
September 3, 2024 - If you have a Collection (it can be a List, Set, LinkedList, Stack etc.) and you want to convert it to a Map then this Collectors.toMap can help you out.
๐ŸŒ
Medium
medium.com โ€บ @luketong โ€บ the-pitfalls-of-using-the-collectors-tomap-9dfeee31b903
The Pitfalls of Using the Collectors.toMap() | by Technical Life | Medium
February 26, 2024 - List<Pair<String, Double>> pairArrayList = new ArrayList<>(3); pairArrayList.add(new Pair<>("version", 12.10)); pairArrayList.add(new Pair<>("version", 12.19)); pairArrayList.add(new Pair<>("version", 6.28)); Map<String, Double> map = pairArrayList.stream() .collect(Collectors .toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2)); public class Pair<K, V> { private final K key; private final V value; public Pair(K key, Vโ€ฆ
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ guide-to-java-8-collectors-tomap
Guide to Java 8 Collectors: toMap()
March 30, 2023 - public static <T,K,U> ... BinaryOperator<U> mergeFunction) The mergeFuction is a function that is called only if there are duplicate key elements present in our final Map that need their values merged and assigned to the one unique key....
๐ŸŒ
Board Infinity
boardinfinity.com โ€บ blog โ€บ collector-tomap-java-tutorial
Collectors toMap() in Java | Board Infinity
July 7, 2023 - We can also provide a Merge Function in addition to the two Mapper Functions: Whenever there is a duplicate key element in the final Map, the mergeFunction gets called to merge their values and assign them to one unique key.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ stream โ€บ Collectors.html
Collectors (Java Platform SE 8 )
3 days ago - public static <T,K,U,M extends ... duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function....
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
Collectors.toMap() vs Collectors.groupingBy() in Java Streams - Java Code Geeks
June 27, 2024 - public class ToMapExample { public static void main(String[] args) { // Example 2: Handling duplicates with merge function List<Product> products = List.of( new Product(1, "Shirt", 1200.0, "Clothing"), new Product(2, "Laptop", 2000.0, "Electronics"), new Product(3, "Keyboard", 80.0, "Accesories"), new Product(4, "Laptop", 2500.0, "Electronics") // Duplicate key with different price ); Map<String, Double> productPriceMap = products.stream() .collect(Collectors.toMap(Product::getName, Product::getPrice, (existing, replacement) -> existing)); System.out.println("Product Price Map: " + productPriceMap); } } This code example code demonstrates handling duplicates with Collectors.toMap() while converting the list of Product objects into a map.