Stream.of("a", "a").collect(Collectors.toMap(String::new, item -> item));
//结果:Exception in thread "main" java.lang.IllegalStateException: Duplicate key a
如果调map.put()方法应该会产生覆盖,不会出现重复key,查看源码发现是调用map.merge(key, value, mergeFunction)把元素放入map里,如果出现key重复会调用mergeFunction方法,Collectors提供了默认的callback方法,出现重复会直接报错。
private static <T> BinaryOperator<T> throwingMerger() {
return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}
修改方案
自己传入mergeFunction,可以调用mergeFunction参数的toMap方法
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);
}
//修改后的方法
Stream.of("a", "a").collect(Collectors.toMap(item -> item item -> item, (oldVal, newVal) -> newVal));