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
posted @ 2020-12-11 15:37  英少  阅读(2826)  评论(0)    收藏  举报