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)
归档时间: |
|
查看次数: |
23680 次 |
最近记录: |