java.lang.IllegalStateException: Duplicate key


java.lang.IllegalStateException: Duplicate key

// list轉map key重復 java.lang.IllegalStateException: Duplicate key DealerImageInfo

如果有形如下方代碼,將List類型的entityList轉為Map類型的entityMap,以Entity::getType(Entity的type字段)為Map的key,以entity對象為Map的value;

Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getType, Function.identity()));

此時如果entityList中entity對象的type有重復,就會拋出此異常;

解決方式:

  1. 保證待轉化的List中各對象作為key的字段不重復;
  2. 使用toMap的重載方法,如下:該方法表示有重復數據時保留最先出現的數據
Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getType, Function.identity(), (entity1,entity2) -> entity1));

toMap方法的三種重載:

toMap(Function<? super T, ? extends K>, Function<? super T, ? extends U>):Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K>, Function<? super T, ? extends U>, BinaryOperator<U>):Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K>, Function<? super T, ? extends U>, BinaryOperator<U>, Supplier<M>):Collector<T, ?, M>

四個參數含義如下:

  1. 獲取Key
  2. 獲取value
  3. key重復時合並規則
  4. 最終的返回類型

第一個方法第3個參數默認置為throwingMerger()方法,表示有重復時拋出異常,就是題目中的異常

第二個方法可以自定義第3個參數,定義為(entity1,entity2) -> entity1,表示保留第一個數據

>參考:https://www.cnblogs.com/han-1034683568/p/8624447.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM