从 Java/Guava 中的某些键的映射中获取所有值?
有没有一种聪明的方法可以从给定某些键的映射中获取所有值?
我想要一个这样的方法:
public static <K, V> Collection<V> getAll(Map<K, V> map, Collection<K> keys)
或者已经是番石榴的方式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这取决于您希望该方法如何工作。例如,
keys
中不在map
中的元素应该被忽略 A) 还是应该 B) 在返回值集合中表示为null
还是 C) 应该是一个错误?还要考虑您是否需要实时视图或包含值的单独集合。对于A,我的偏好是:
这将结果限制为映射中实际存在的键的值,并且应该相对有效,即使映射比您设置的键集大得多。想。当然,您可能希望将该结果复制到另一个集合中,具体取决于您想用它做什么。
对于 B,您可以使用 @Michael Brewer-Davis 的解决方案,但
Functions.forMap(map, null)
除外。对于C,您首先要检查
map.keySet().containsAll(keys)
,如果false
则抛出错误,然后使用 @Michael Brewer-Davis 的解决方案...但请注意,除非您将结果复制到另一个集合中,否则从map
中删除条目可能会导致代码出现IllegalArgumentException
在某个时刻使用返回的集合。This depends on how you want the method to work. For example, should elements in
keys
that aren't inmap
A) just be ignored or should they B) be represented asnull
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:
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 iffalse
, then use @Michael Brewer-Davis's solution... but be aware that unless you then copied the result in to another collection, removing an entry frommap
could cause anIllegalArgumentException
for code using the returned collection at some point.我同意skaffman的回答,只是不同意他的结论(我认为这比手动迭代更好)。
这里是拼写出来的:
另外,这是一个非 Guava 版本(Java 8 或更高版本):
I agree with skaffman's answer, just not with his conclusion (I think this is better than manual iteration).
Here it is spelled out:
Also, here's a non-Guava version (Java 8 or higher):
我想您可以使用 Guava 的 Maps.filteredKeys() ,传入与您所需的键匹配的谓词,但这并不比手动迭代更好。
You could, I suppose use Guava's
Maps.filteredKeys()
, passing in aPredicate
which matches your desired keys, but it's not really any better than manual iteration.使用番石榴:
Collections2.transform(keys, Functions.forMap(map));
Using guava:
Collections2.transform(keys, Functions.forMap(map));
Java8 Streams:
或者如果您担心丢失键:
或者如果您需要多个线程来工作(很少见,请参阅@tkruse 评论):
Java8 Streams:
Or if you're concerned about missing keys:
Or if you need multiple threads to work (rarely, see @tkruse comment):