Java 8 Collectors.toMap SortedMap(Java 8 Collectors.toMap 排序地图)
问题描述
我正在使用 Java 8 lambda,并希望使用 Collectors
toMap
来返回 SortedMap
.我能想到的最好的方法是调用以下 Collectors
toMap
方法,其中虚拟 mergeFunction
和 mapSupplier
相等到 TreeMap::new
.
I'm using Java 8 lambdas and want to use Collectors
toMap
to return a SortedMap
. The best I can come up with is to call the following Collectors
toMap
method with a dummy mergeFunction
and mapSupplier
equal to 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
实现方式相同,如下所示:
I don't want to pass in a merge function though, as I just want throwingMerger()
, in the same way as the basic toMap
implementation as follows:
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
的最佳实践方法是什么?
What would be the best practise method of using Collectors
to return a SortedMap
?
推荐答案
我认为没有比这更好的了:
I don't think you can get much better than this:
.collect(Collectors.toMap(keyMapper, valueMapper,
(v1,v2) ->{ throw new RuntimeException(String.format("Duplicate key for values %s and %s", v1, v2));},
TreeMap::new));
其中 throw
lambda 与 throwingMerger()
相同,但我不能直接调用它,因为它是包私有的(当然,您可以始终使自己的静态像 throwingMerger()
这样的方法是.)
where the throw
lambda is the same as throwingMerger()
but I can't directly call that since it's package private (you can of course always make your own static method for that like throwingMerger()
is. )
这篇关于Java 8 Collectors.toMap 排序地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 Collectors.toMap 排序地图
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01