How to filter a map with Java stream api?
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());
You can achieve this by using something like this :
List<String> values = map.entrySet()
.stream()
.filter(entry -> picks.contains(entry.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
values.forEach(System.out::println);
Output:
f
a
However it might not be efficient as List::contains
is O(N). Consider using a Set
(for example HashSet
) instead of List
for picks
as HashSet::contains
is O(1).