Search code examples
javajava-stream

Duplicate key (attempted merging values x and x)


I have a simple class:

public class Rule {
    int id;
    long cableType;
}

I want to convert a list with objects of this class to Map<Integer, Long>, so I wrote code:

Map<Integer, Long> 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 merging values 31 and 30)

How can I fix this?


Solution

  • To avoid this error, you need to take one of the duplicate entries for example, to do this you need:

    .collect(Collectors.toMap(Rule::getId, Rule::getCableType, (r1, r2) -> r1));