我正在使用 Java 8 lambda,并希望使用它Collectors toMap来返回一个SortedMap. 我能想到的最好的方法是Collectors toMap用一个哑元mergeFunction和mapSupplier等于调用以下方法TreeMap::new。
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier) {
BiConsumer<M, T> accumulator = (map, element) -> map.merge(keyMapper.apply(element),
valueMapper.apply(element), mergeFunction);
return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
}
我不想传入一个合并函数,就像我想要throwingMerger()的那样,以与基本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);
}
Collectors使用返回 a的最佳实践方法是SortedMap什么?