简体   繁体   中英

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

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?

You can use Stream s:

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]

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM