曹耘豪的博客

Java中默认Collectors.toMap的坑

两参数的toMap的合并策略是直接抛出异常,需要额外注意。源码如下:

1
2
3
4
5
6
7
8
9
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);
}

private static <T> BinaryOperator<T> throwingMerger() {
return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}
   / 
・页阅读量: ・站访问量: ・站访客数: