CodexBloom - Programming Q&A Platform

Java 17 Stream API Collectors.toMap() throws IllegalStateException when merging values

šŸ‘€ Views: 730 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-18
java stream collectors java-17 Java

I'm not sure how to approach I'm relatively new to this, so bear with me. I'm building a feature where I'm working with an scenario when trying to merge entries while using `Collectors.toMap()` in Java 17. The question arises when two keys in the stream are identical, which leads to an `IllegalStateException` due to duplicate keys. Here is a simplified version of my code: ```java import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Item> items = Arrays.asList( new Item("A", 1), new Item("B", 2), new Item("A", 3) ); Map<String, Integer> itemMap = items.stream() .collect(Collectors.toMap( Item::getName, Item::getValue, (oldValue, newValue) -> oldValue + newValue )); } } class Item { private String name; private int value; public Item(String name, int value) { this.name = name; this.value = value; } public String getName() { return name; } public int getValue() { return value; } } ``` When I run this code, I get the following exception: ``` Exception in thread "main" java.lang.IllegalStateException: Duplicate key A (attempted merging values 1 and 3) ``` I've tried using the merge function `(oldValue, newValue) -> oldValue + newValue`, but I still receive the exception. I’m not sure if I'm implementing this correctly or if there's a different approach I should be considering for handling duplicates. Is there a better way to collect the map without causing this exception, or do I need to preprocess the list before collecting it? Any insights would be greatly appreciated! I recently upgraded to Java LTS. I'd really appreciate any guidance on this. Any help would be greatly appreciated!