Duplicate key (attempted merging values x and x)

Viewed 5990

I have this simple class

public class Rule {
    int id;
    long cableType;

I'm want to convert list with this classes to Map<Integer, Long> I wrote this code:

Map<Integer, Long> map = ruleList.stream().collect(Collectors.toMap(Rule::getId, Rule::getCableType));

But in this list I have the 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 I can fix this?

1 Answers

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));
Related