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有重復,就會拋出此異常;
解決方式:
- 保證待轉化的List中各對象作為key的字段不重復;
- 使用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>
四個參數含義如下:
- 獲取Key
- 獲取value
- key重復時合並規則
- 最終的返回類型
第一個方法第3個參數默認置為throwingMerger()方法,表示有重復時拋出異常,就是題目中的異常
第二個方法可以自定義第3個參數,定義為(entity1,entity2) -> entity1,表示保留第一個數據
>參考:https://www.cnblogs.com/han-1034683568/p/8624447.html