java.lang.IllegalStateException: Duplicate key
// list转map key重复
java.lang.IllegalStateException: Duplicate key DealerImageInfo
出现原因
当使用java.util.Collection
的stream()
方法将集合转为Map
时,如果key
有重复就会抛出此异常。
**例:**如果有形如下代码
//将List类型的entityList转为entityMap,Entity的id字段作为key,entity对象为value
//Entity::getId:获取Entity的id字段
//Function.identity()等同于x->x,将输入作为输出,即将遍历的对象最为value
Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getId, Function.identity()));
此时如果entityList
中entity
对象的id
有重复,就会抛出此异常;
解决方法
- 保证待转化的List中各对象作为key的字段不重复(业务方式处理,不做介绍);
- 使用toMap的重载方法。
Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getId, Function.identity(), (var1, var2) -> var1));
这种方式是toMap()
方法新加一个参数,该参数是重复数据的处理规则。示例中使用这种方式是保留第一条数据,读者也可以根据需求写第三个参数。
自此异常处理完毕,下面写一些toMap的重载方法。
番外:toMap的重载方法
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>
这三个重载方法最终执行方法是最后一个,前两个都是加入默认参数后调用第三个方法;
方法参数含义如下:
- 获取
Map
的Key
- 获取
Map
的value
key
重复时合并规则- 最终的返回类型 (不传时默认返回
Map
类型)
第一个方法第3个参数默认置为throwingMerger()
方法,表示有重复时抛出异常,就是题目中的异常
第二个方法可以自定义第3个参数,定义为(entity1,entity2) -> entity1
,表示保留第一个数据
源码:
// 只有两个参数的toMap
// 这个方法缺省的重复数据处理规则是调用throwingMerger()方法
// 返回的Map是HashMap
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
// throwingMerger方法对重复数据直接抛出异常,这个异常就是我们见到的异常
private static <T> BinaryOperator<T> throwingMerger() {
return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}
// 三个参数的方法可以指定重复数据的处理规则
// 返回的Map是HashMap
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
}
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier) {
BiConsumer<M, T> accumulator
= (map, element) -> map.merge(keyMapper.apply(element),
valueMapper.apply(element), mergeFunction);
return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
}