java duplicate key_java.lang.IllegalStateException: Duplicate key 1

前言

昨天项目报错

java.lang.IllegalStateException: Duplicate key 1

代码如下:

Map userId2BatchId = userLevelList.stream().collect(Collectors.toMap(RazUserLevel::getUserId, RazUserLevel::getBatchId);

原因是存在重复key导致

正文

查看toMap文档

toMap

public static Collector> toMap(Function super T,? extends K> keyMapper,

Function super T,? extends U> valueMapper)

1

2

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

API Note:

It is common for either the key or the value to be the input elements. In this case, the utility method Function.identity() may be helpful. For example, the following produces a Map mapping students to their grade point average:

Map studentToGPA students.stream()

.collect(toMap(Functions.identity(), student -> computeGPA(student)));

1

2

And the following produces a Map mapping a unique identifier to students:

Map studentIdToStudent

students.stream().collect(toMap(Student::getId, Functions.identity());

如果在最后生成map的时候,mapped到的keys中如果包含重复的键(通过key类型的equals方法来判断),则会抛出异常IllegalStateException。但是,后面也提到,如果keys中包含有相同的键,则可以使用toMap(Function, Function, BinaryOperator)方法来替代。

我的改进如下:

Map userId2BatchId = userLevelList.stream().collect(Collectors.toMap(RazUserLevel::getUserId, RazUserLevel::getBatchId, (e1, e2) -> e1));

也就是有重复值的时候,我取先进来的值,也就是e1。

总结

java8不熟,查api

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值