日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

java duplicate key_java.lang.IllegalStateException: Duplicate key 1

發(fā)布時(shí)間:2023/12/18 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java duplicate key_java.lang.IllegalStateException: Duplicate key 1 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

昨天項(xiàng)目報(bào)錯(cuò)

java.lang.IllegalStateException: Duplicate key 1

代碼如下:

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

原因是存在重復(fù)key導(dǎo)致

正文

查看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的時(shí)候,mapped到的keys中如果包含重復(fù)的鍵(通過key類型的equals方法來判斷),則會(huì)拋出異常IllegalStateException。但是,后面也提到,如果keys中包含有相同的鍵,則可以使用toMap(Function, Function, BinaryOperator)方法來替代。

我的改進(jìn)如下:

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

也就是有重復(fù)值的時(shí)候,我取先進(jìn)來的值,也就是e1。

總結(jié)

java8不熟,查api

總結(jié)

以上是生活随笔為你收集整理的java duplicate key_java.lang.IllegalStateException: Duplicate key 1的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。