[英]How to get List<Y> from Map<X,Y> by providing List<X> using google collection?
I have a Map<X, Y>
and List<X>
, I would like to extract the values from Map<X, Y>
by providing the List<X>
, which will result in List<Y>
. 我有一个
Map<X, Y>
和List<X>
,我想通过提供List<X>
从Map<X, Y>
提取值,这将导致List<Y>
。 One way to do this is 一种方法是
List<X> keys = getKeys();
Map<X, Y> map = getMap();
List<Y> values = Lists.newArrayListWithCapacity(keys.size());
for(X x : keys){
values.add(map.get(x));
}
Now again I need to remove nulls in values ( List<Y>
) by using Predicate or something. 现在我需要使用Predicate或其他东西删除值(
List<Y>
)中的空值。 Any better way to do this? 有更好的方法吗?
Is there any good reason why this method isn't there in google collections library? 谷歌馆藏库中没有这种方法有什么好的理由吗?
Something like this: 像这样的东西:
List<Y> values = Lists.newArrayList(
Iterables.filter(
Lists.transform(getKeys(), Functions.forMap(getMap(), null),
Predicates.notNull()));
Same concept as axtavt's answer , but using FluentIterable
(reads sequentially instead of inside-out): 与axtavt的答案相同的概念,但使用
FluentIterable
(顺序读取而不是从里到外读取):
List<Y> values = FluentIterable
.from(keys)
.transform(Functions.forMap(map, null))
.filter(Predicates.notNull())
.toList();
@axtavt's answer would probably be the most efficient given your exact requirements. 鉴于您的确切要求, @ axtavt的答案可能是最有效的。 If your
List
of keys were instead a Set
, something like this would be my preference: 如果您的密钥
List
是一个Set
,那么这样的东西将是我的偏好:
List<Y> values = Lists.newArrayList(
Maps.filterKeys(getMap(), Predicates.in(getKeys())).values());
I think a special method for doing this isn't in Guava because it's not generally useful enough. 我认为这样做的一种特殊方法不是在番石榴中,因为它通常不够用。 Plus, as you can see there are ways of composing things Guava does provide to achieve this.
另外,正如您所看到的,有很多方法可以组合Guava为实现这一目标而提供的功能。 Guava focuses on providing building blocks, with specific methods for operations that are very common.
Guava专注于提供构建模块,具有非常常见的特定操作方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.