Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

hash

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?

like image 267
Dhiral Kaniya Avatar asked Sep 04 '19 13:09

Dhiral Kaniya


People also ask

Can HashMap keys have multiple values?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

How many values can a HashMap hold?

A HashMap in Java can have a maximum of 2^30 buckets for storing entries - this is because the bucket-assignment technique used by java. util. HashMap requires the number of buckets to be a power of 2, and since ints are signed in Java, the maximum positive value is 2^31 - 1, so the maximum power of 2 is 2^30.


1 Answers

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]
like image 113
Eran Avatar answered Sep 30 '22 22:09

Eran