Collector.toMap,Map中的key不能重复,如果重复的话,会抛出异常

1.报错

Exception in thread "main" java.lang.IllegalStateException: Duplicate key http://www.google.com
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1253)
    at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)

2.解决

通过查看Collectors.toMap的代码及注释我们会发现:

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);
}
If the mapped keys contains duplicates (according to Object#equals(Object)), 
an IllegalStateException is thrown when the collection operation is performed. 
If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

所以说呢,我们使用的Collectors.toMap的方法是不支持key重复的,并且如果有重复的时候,建议我们使用toMap(Function, Function, BinaryOperator) 方法来替换使用,并且我们还可以定义当key重复的时候,是使用旧的数据还是使用新的数据
即:

Map<String, String> memberMap = list.stream()
									.collect(Collectors.toMap(Member::getId, Member::getImgPath,(oldValue,newValue) -> oldValue));
posted @ 2019-11-23 18:05  叶落无蝉鸣  阅读(1145)  评论(0编辑  收藏  举报