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