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
總結
以上是生活随笔為你收集整理的java duplicate key_java.lang.IllegalStateException: Duplicate key 1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 核心价值观
- 下一篇: python在地图上标注点_只要两步,用