Java 8 Stream filter all the values from a map given a list of keys

Viewed 1724

I have a Map<String, String>

I want to stream all the values in a List<String> I call keys.

How can I get this to return the Values from the map?

Map like this:

("Frank", "Car")
("Bob", "Bike")
("Jim", "Truck")

List of keys i give it:

["Frank","Jim"]

Expected result:

["Car","Truck"]

I tried this but it just prints the keys not the values.

keys.stream()
    .filter(map::containskey)
    .collect(Collectors.toList())
2 Answers

You just check, if keys are present in Map and if they are, then you keep them in the result stream. To replace keys with values you can use map()

public static void main(String[] args) {
    Map<String, String> cars = new HashMap<>();
    cars.put("Frank", "Car");
    cars.put("Bob", "Bike");
    cars.put("Jim", "Truck");

    List<String> keys = new ArrayList<>();
    keys.add("Frank");
    keys.add("Jim");
    List<String> result = keys
            .stream()
            .filter(cars::containsKey)
            .map(cars::get)
            .collect(Collectors.toList());
    System.out.println(result);
}

Output:

[Car, Truck]

Stream and filter the entries:

map.entrySet().stream()
      .filter(e -> keys.contains(e.getKey()))
      .map(Map.Entry::getValue)
      .collect(Collectors.toList())
Related