How to get multiple values for multiple keys from Hashmap in a single operation?

You can take an input Set having the keys to query for and use stream operations Stream#filter and Stream#map to filter and map the results and finally collect the values into a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Hello");
map.put(2, "World");
map.put(3, "New");
map.put(4, "Old");

Set<Integer> keys = Set.of(1, 2);

List<String> values = map.entrySet()
                         .stream()
                         .filter(ent -> keys.contains(ent.getKey()))
                         .map(Map.Entry::getValue)
                         .collect(Collectors.toList());
System.out.println(values);

Output:

[Hello, World]

IntStream.of(1, 2)
        .map(map::get)
        .collect(Collectors.toList());

You can use Streams:

List<Integer> keys = List.of(1,2);
List<String> values = 
    keys.stream()
        .map(map::get)
        .filter(Objects::nonNull) // get rid of null values
        .collect(Collectors.toList());

This will result in the List:

[Hello, World]

Tags:

Java

Hash

Hashmap