Rob*_*ain 64 java lambda java-8 java-stream collectors
我正在使用Java 8 lambdas并希望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);
}
Run Code Online (Sandbox Code Playgroud)
我不想传递合并函数,正如我想要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);
}
Run Code Online (Sandbox Code Playgroud)
什么是使用Collectors
返回的最佳实践方法SortedMap
?
dka*_*zel 70
我认为你不能比这更好:
.collect(Collectors.toMap(keyMapper, valueMapper,
(v1,v2) ->{ throw new RuntimeException(String.format("Duplicate key for values %s and %s", v1, v2));},
TreeMap::new));
Run Code Online (Sandbox Code Playgroud)
其中throw
lambda是相同的,throwingMerger()
但我不能直接调用它,因为它的包是私有的(你当然总是可以为它创建自己的静态方法throwingMerger()
.)
根据dkatzel确认没有一个很好的API方法,我选择维护我自己的自定义Collectors类:
public final class StackOverflowExampleCollectors {
private StackOverflowExampleCollectors() {
throw new UnsupportedOperationException();
}
private static <T> BinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
}
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, Supplier<M> mapSupplier) {
return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), mapSupplier);
}
}
Run Code Online (Sandbox Code Playgroud)
似乎在没有定义自己的throwingMerger()
方法或使用显式lambda的情况下,没有标准的方法可以做到这一点.在我的StreamEx库中,我定义了toSortedMap
也使用我自己的方法throwingMerger()
.
执行此操作的另一种方法是允许Collectors.toMap()返回将要返回的任何地图,然后将其传递给新的TreeMap <>()。
需要注意的是,这仅在您的“ hashCode()+ equals()”和“ compareTo”一致时才有效。如果不一致,那么HashMap最终将删除与TreeMap不同的键集。
如果您使用番石榴库,那么您可以使用:
.collect(ImmutableSortedMap.toImmutableSortedMap(comparator, keyMapper, valueMapper));
Run Code Online (Sandbox Code Playgroud)
生成的映射将是 aSortedMap
并且也是不可变的。
归档时间: |
|
查看次数: |
31809 次 |
最近记录: |