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

Dhiral Kaniya :

I want to get values for more than one key using HashMap, for example:

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

Now I want to combine values for 1 and 2 and create a List<String> output. I can do this with 2 times get an operation or create one function that takes a key list and return a list of values.

But is there any in-built util function that do the same job?

Eran :

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]

Guess you like

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