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 aSet
.Let’s say,for example,you have a
Map<String,String>
that contains
both “1” and “01” as keys. They are both distinctString
s,and so the
Map
can legally contain both as keys. If you transform them using
Long.valueOf(String)
,they both map to the value1
. 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
transformedMap
,would have no way of enforcing unique keys
and would therefore break the contract of aMap
.
这是真的,但实际上我不明白为什么它不是因为:
>当密钥变换发生时,如果2个密钥“合并”,可能会引发运行时异常,或者我们可以传递一个标志来指示Guava为新计算的密钥获取多个可能值的任何值(failfast / failsafe可能性)
>我们可以有一个产生Multimap的Maps.transformKeys
在做这样的事情时我看不到有什么缺点吗?