Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


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));
like image 63
YCF_L Avatar answered Sep 05 '25 06:09

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!