从Map中获取Java / Guava中的某些键的所有值? [英] Get all Values from a Map for some Keys in Java/Guava?

查看:525
本文介绍了从Map中获取Java / Guava中的某些键的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个聪明的方法来获取地图中的所有值给定一些键?



我想要一个这样的方法:

  public static< K,V&集合< V> getAll(Map< K,V> map,Collection< K> keys)

方法?

解决方案

这取决于你想要的方法的工作方式。例如,如果中的元素不在 map A)忽略或应该将它们 B)表示为返回值集合中的 null ,或者应该 C)对于 A ,我的偏好设置为:

如果您要查看实时视图或包含值的单独集合,

  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中的某些键的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆