How to get list <Y> from map <X, Y> by providing List <X> using google collection?

I have Map<X, Y> and List<X> , I would like to extract values ​​from Map<X, Y> by providing List<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 the zeros in the values ​​( List<Y> ) using Predicate or something like that. Any better way to do this?
Is there a good reason why this method is not in the google collections library?

+4
source share
3 answers

Something like that:

 List<Y> values = Lists.newArrayList( Iterables.filter( Lists.transform(getKeys(), Functions.forMap(getMap(), null), Predicates.notNull())); 
+4
source

The @axtavt answer is likely to be most effective based on your exact requirements. If your List keys were instead of Set , then this would be preferable:

 List<Y> values = Lists.newArrayList( Maps.filterKeys(getMap(), Predicates.in(getKeys())).values()); 

I think that a special method for this does not exist in Guava, because it is usually not useful enough. In addition, as you can see, there are ways to create the things that Guava really provides to achieve this. Guava focuses on providing building blocks, with specific methods for operations that are very common.

0
source

Same concept as axtavt answer , but using FluentIterable (read sequentially instead of inside out):

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

Source: https://habr.com/ru/post/1340217/


All Articles