在2个参数的版本
Collectors.toMap()采用的是
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);}要使用4参数版本,您可以替换:
Collectors.toMap(Function.identity(), String::length)
与:
Collectors.toMap( Function.identity(), String::length, (u, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); }, linkedHashMap::new)为了使它更简洁,请编写一个新
tolinkedMap()方法并使用该方法:
public class MoreCollectors{ public static <T, K, U> Collector<T, ?, Map<K,U>> tolinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return Collectors.toMap( keyMapper, valueMapper, (u, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); }, linkedHashMap::new ); }}


