集合进行stream操作,Collectors.toMap转换成map时,如果list集合中有重复数据,更确切的说,是作为key的实例的属性值,存在重复,下面的写法就会报错:
List<User> a = new ArrayList<>();for (int i=0;i<5;i++) {User u = new User();u.setName("a");u.setHome("b");a.add(u);}Map<String, User> collect = a.stream().collect(Collectors.toMap(User::getName, t -> t));
错误:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key a (attempted merging values User{name='a', home='b'} and User{name='a', home='b'})at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)at com.shebao.controller.TestController.main(TestController.java:25)
这是因为使用方法时没有指定mergeFunction
public static <T, K, U>Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper) {return new CollectorImpl<>(HashMap::new,uniqKeysMapAccumulator(keyMapper, valueMapper),uniqKeysMapMerger(),CH_ID);}
uniqKeysMapAccumulator这个方法,没有指定mergeFunction时会在key重复了的时候直接丢出
if (u != null) throw duplicateKeyException(k, u, v);
解决方法:
指定mergeFunction,方法如下:
a.stream().collect(Collectors.toMap(User::getName, t -> t,(oldValue,newValue) -> newValue));
(oldValue,newValue) -> newValue这里指定了当重复的时候,使用新的值。
可以看看源码写法:
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);}