这个问题已经发布在这里: 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 distinctString
s, and so theMap
can legally contain both as keys. If you transform them usingLong.valueOf(String)
, though, 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
, though, would have no way of enforcing unique keys and would therefore break the contract of aMap
.
这个是对的,但其实我不明白为什么不这样做是因为:
当键转换发生时,如果 2 个键被“合并”,可能会引发运行时异常,或者我们可以传递一个标志来指示 Guava 为新计算的多个可能值取任何值关键(failfast/failsafe 可能性)
我们可以有一个 Maps.transformKeys 来生成一个 Multimap
这样做有没有我看不到的缺点?
最佳答案
正如@CollinD 所建议的,没有办法以惰性方式执行此操作。实现get
,您必须使用转换函数转换所有键(以确保发现任何重复项)。
所以申请Function<K,NewK>
至 Map<K,V>
出来了。
您可以安全地申请 Function<NewK,K>
到 map :
V value = innerMap.get( fn.apply(newK) );
我没有看到 Guava 的简写形式——它可能不够有用。您可以通过以下方式获得类似的结果:
Function<NewK,V> newFn = Functions.compose(Functions.forMap(map), fn);
关于java - 为什么 Guava 不提供转换映射键的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13991710/