【发布时间】:2021-10-24 16:25:14
【问题描述】:
我有这个简单的课程
public class Rule {
int id;
long cableType;
我想将包含此类的列表转换为Map<Integer, Long>
我写了这段代码:
Map<Integer, Long> map = ruleList.stream().collect(Collectors.toMap(Rule::getId, Rule::getCableType));
但在这个列表中,我有 (1, 10), (1,40) 这样的重复项
当我运行这段代码时,我得到了这个异常:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 21 (attempted merging values 31 and 30)
我该如何解决这个问题?
【问题讨论】:
-
您不能在一个简单的
Map中将两个不同的值映射到同一个键。 -
我相信它需要一个预处理。但是你想对重复的值做什么?对 cableType 求和,保留第一个,保留最后一个,...
-
您要复制一份或全部?
标签: java java-stream