为什么番石榴不提供转换地图关键点的方法 [英] Why Guava does not provide a way to transform map keys
问题描述
这个问题已经在这里发布了: 如何转换Map< String,String>映射< Long,String>使用番石榴
This question is kind of already posted here: How to convert Map<String, String> to Map<Long, String> using guava
我认为CollinD的答案是适当的:
I think the answer of CollinD is appropriate:
Guava的所有转换和过滤方法都会产生延迟 结果...函数/谓词仅在需要时才应用 使用对象.他们不创建副本.因此, 转换很容易破坏
Set
的要求.
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
.
例如,假设您有一个Map<String, String>
包含
同时将"1"和"01"作为键.它们都是不同的String
,因此
Map
可以合法地包含两者作为密钥.如果使用
但是,Long.valueOf(String)
都映射到值1
.他们是
不再使用不同的键.如果您这样做不会破坏任何东西
创建地图的副本并添加条目,因为任何重复项
键将覆盖该键的先前条目.懒惰的
但是,转换后的Map
无法强制执行唯一键
因此会破坏Map
的合同.
Let's say, for example, you have a Map<String, String>
that contains
both "1" and "01" as keys. They are both distinct String
s, and so the
Map
can legally contain both as keys. If you transform them using
Long.valueOf(String)
, though, 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
, though, would have no way of enforcing unique keys
and would therefore break the contract of a Map
.
这是真的,但实际上我不明白为什么不这样做,原因是:
This is true, but actually I don't understand why it is not done because:
-
当键转换发生时,如果合并"了两个键,则可能引发运行时异常,或者我们可以传递一个标志来指示Guava为新计算的值取多个可能值中的任何一个值键(故障/故障安全可能性)
When the key transformation happen, if 2 keys are "merged", a runtime exception could be raised, or we could pass a flag to indicate to Guava to take any value of the multiple possible values for the newly computed key (failfast/failsafe possibilities)
我们可以有一个Maps.transformKeys来生成一个Multimap
We could have a Maps.transformKeys which produces a Multimap
在做这些事情时我没有看到缺点吗?
Is there a drawback I don't see in doing such things?
推荐答案
正如@CollinD所建议的那样,没有办法以懒惰的方式执行此操作.要实现get
,必须使用转换函数转换所有键(以确保发现任何重复项).
As @CollinD suggests, there's no way to do this in a lazy way. To implement get
, you have to convert all the keys with your transformation function (to ensure any duplicates are discovered).
因此将Function<K,NewK>
应用于Map<K,V>
的操作已退出.
So applying Function<K,NewK>
to Map<K,V>
is out.
您可以安全地将Function<NewK,K>
应用于地图:
You could safely apply Function<NewK,K>
to the map:
V value = innerMap.get( fn.apply(newK) );
我没有看到Guava的简写-可能只是不够用.您可以通过以下方式获得类似的结果:
I don't see a Guava shorthand for that--it may just not be useful enough. You could get similar results with:
Function<NewK,V> newFn = Functions.compose(Functions.forMap(map), fn);
这篇关于为什么番石榴不提供转换地图关键点的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!