sree raja
sree raja

Reputation: 177

How to get values from a Map with a list of keys using Java8 streams

I have a Map "M" and a list "L", now i want get the values from that map "M" using those list of keys available in "L". I want to use java 8 Stream concept can anyone help on this.

I coded to print those values but what i need is to get values into a list

list.stream().forEach(s->{System.out.println(map.get(s));});

Upvotes: 2

Views: 116

Answers (1)

Eran
Eran

Reputation: 393801

map each element of the List to the corresponding value in the Map and collect to a List:

List<String> values =
    list.stream()
        .map(map::get)
        .collect(Collectors.toList());

You might want to consider eliminating null values (which result from keys not present in the Map).

Upvotes: 8

Related Questions