java – 为什么Guava不提供一种转换地图键的方法

前端之家收集整理的这篇文章主要介绍了java – 为什么Guava不提供一种转换地图键的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题已经在这里发贴了:
How to convert Map<String,String> to Map<Long,String> using guava

我认为CollinD的答案是适当的:

All of Guava’s methods for transforming and filtering produce lazy
results… the function/predicate is only applied when needed as the
object is used. They don’t create copies. Because of that,though,a
transformation can easily break the requirements of a Set.

Let’s say,for example,you have a Map<String,String> that contains
both “1” and “01” as keys. They are both distinct Strings,and so the
Map can legally contain both as keys. If you transform them using
Long.valueOf(String),they both map to the value 1. They are
no longer distinct keys. This isn’t going to break anything if you
create a copy of the map and add the entries,because any duplicate
keys will overwrite the prevIoUs entry for that key. A lazily
transformed Map,would have no way of enforcing unique keys
and would therefore break the contract of a Map.

这是真的,但实际上我不明白为什么它不是因为:

>当密钥变换发生时,如果2个密钥“合并”,可能会引发运行时异常,或者我们可以传递一个标志来指示Guava为新计算的密钥获取多个可能值的任何值(failfast / failsafe可能性)
>我们可以有一个产生Multimap的Maps.transformKeys

在做这样的事情时我看不到有什么缺点吗?

解决方法

正如@CollinD所说,没有办法以懒惰的方式做到这一点.要实现get,您必须使用转换函数转换所有键(以确保发现任何重复项).

因此,应用函数< K,NewK>映射< K,V>出来了

您可以安全地应用Function< NewK,K>到地图上:

V value = innerMap.get( fn.apply(newK) );

我没有看到番石榴的速记 – 它可能不够有用.您可以获得类似的结果:

Function<NewK,V> newFn = Functions.compose(Functions.forMap(map),fn);
原文链接:https://www.f2er.com/java/125079.html

猜你在找的Java相关文章