| 
                         这个问题已经在这里发贴了: 
   
 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);                         (编辑:莱芜站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |