重复键(尝试合并值 x 和 x)

23 java java-stream

我有一个简单的课程:

public class Rule {
    int id;
    long cableType;
}
Run Code Online (Sandbox Code Playgroud)

我想将包含此类对象的列表转换为Map<Integer, Long>,所以我编写了代码:

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

该列表有一个重复项(1, 10), (1,40),当我运行此代码时,我收到此异常:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 21 (attempted merging values 31 and 30)
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

YCF*_*F_L 47

为了避免此错误,您需要采用重复条目之一,例如,为此您需要:

.collect(Collectors.toMap(Rule::getId, Rule::getCableType, (r1, r2) -> r1));
Run Code Online (Sandbox Code Playgroud)

  • 不错,不知道收集器可以使用 lambda 来修复重复的键 (3认同)
  • API 文档[此处](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function。函数-java.util.function.BinaryOperator-)。 (2认同)