问题描述
有一个聪明的方法来获取地图中的所有值给定一些键?
我想要一个这样的方法:
public static< K,V&集合< V> getAll(Map< K,V> map,Collection< K> keys)
方法?
这取决于你想要的方法的工作方式。例如,如果键
中的元素不在 map
A)忽略或应该将它们 B)表示为返回值集合中的 null
,或者应该 C)?
Collection< V> values = Collections2.transform(
Collections2.filter(keys,Predicates.in(map.keySet()),
Functions.forMap(map));
这会将结果限制为实际在地图中的键的值,并且应该也是相对高效的,即使地图比集合大得多
对于 B
/ strong>,你可以使用@Michael Brewer-Davis的解决方案,除了 Functions.forMap(map,null)
。 对于 C ,您首先要检查 map.keySet()。containsAll(keys)
code> false ,然后使用@Michael Brewer-Davis的解决方案...但请注意,除非您将结果复制到另一个集合,从 map
可能会导致 IllegalArgumentException
对于使用返回的集合的代码。
Is there a smart way to get all Values from a Map given some Keys?
I would like a method like this:
public static <K, V> Collection<V> getAll(Map<K, V> map, Collection<K> keys)
or is already a guava way?
This depends on how you want the method to work. For example, should elements in keys
that aren't in map
A) just be ignored or should they B) be represented as null
in the returned values collection or should that C) be an error? Also consider whether you want a live view or a separate collection containing the values.
For A, my preference would be:
Collection<V> values = Collections2.transform(
Collections2.filter(keys, Predicates.in(map.keySet()),
Functions.forMap(map));
This limits the result to values for keys that are actually in the map and should be relatively efficient as well, even if the map is much larger than the set of keys you want. Of course, you may want to copy that result in to another collection depending on what you want to do with it.
For B, you'd use @Michael Brewer-Davis's solution except with Functions.forMap(map, null)
.
For C, you'd first want to check that map.keySet().containsAll(keys)
and throw an error if false
, then use @Michael Brewer-Davis's solution... but be aware that unless you then copied the result in to another collection, removing an entry from map
could cause an IllegalArgumentException
for code using the returned collection at some point.
这篇关于从Map中获取Java / Guava中的某些键的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!