开发者

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&开发者_C百科lt;X>, which will result in 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. 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()));


@axtavt's answer would probably be the most efficient given your exact requirements. If your List of keys were instead a Set, something like this would be my preference:

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 focuses on providing building blocks, with specific methods for operations that are very common.


Same concept as axtavt's answer, but using FluentIterable (reads sequentially instead of inside-out):

List<Y> values = FluentIterable
    .from(keys)
    .transform(Functions.forMap(map, null))
    .filter(Predicates.notNull())
    .toList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜