How to filter a map with Java stream api?

Patty :
Map<Integer, String> map = new HashMap<>();
map.put(1, "f");
map.put(2, "i");
map.put(3, "a");
map.put(4, "c");....etc

Now I have a list:

List<Integer> picks = {1,3}

I would like to get back a list of Strings, ie, values from map that matches the key values, found in the 'pick' list.So, I am expecting to get back {"f", "a"} as result. Is there a way to use java stream api to do it in elegant way?

When there is one value , I am doing it this way:

map.entrySet().stream()
            .filter(entry -> "a".equals(entry.getValue()))
            .map(entry -> entry.getValue())
            .collect(Collectors.toList())

But getting hard time when there is a list of keys/picks to filter with.

Fullstack Guy :

You can use List.contains() in the Stream#filter to only accept those values which are present in the list:

List<String> result = map.entrySet()
                         .stream()
                         .filter(ent -> picks.contains(ent.getKey()))
                         .map(Map.Entry::getValue)     
                         .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138757&siteId=1