我正在使用Java 8的Lambda表达式,并想使用
Collectors
toMap
方法返回一个SortedMap
。我能想到的最好的方法是使用一个虚拟的mergeFunction
和将mapSupplier
设置为TreeMap::new
来调用下面的Collectors
toMap
方法。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);
}
我不想传入一个合并函数,只想要像基本的toMap
实现中一样使用 throwingMerger()
:
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
返回一个SortedMap
?
k
并不是像字母所暗示的那样是键,而是用于合并的二进制操作的第一个值。 - antak(k,v)
更改为(v1,v2)
,因为lambda参数实际上是两个冲突的值。JDK中的throwingMerger()
是错误的。希望你不介意。 :) - Christoffer Hammarström