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?
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With