Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value of HashMap using part of the key

I have an HashMap(String,Object). The key is combination of more than 1 unique ID. I have an input, a string which is part of the key(1 unique ID). I need to take the value in HashMap using that part of the key i have without iterating thousands of values in HashMap.

Can we achieve it using any Regex statement in HashMap.get()?

My Key is xxx.yyy.zzz where combination of xxx.zzz is unique throughout the Map. I have xxx and zzz as input. Also i have set of possible values of yyy(5-6 possibilities which may increase as well)for a given zzz.

I have two options to solve this now.

  1. Map.Entry to check whether key starts and ends with xxx and zzz respectively
  2. Trial and Error Method i. Form key xxx.yyy.zzz with all possible yyys and check for whether the key is present or not using .contains() ii. But this way, if i do .contains() 5-6 times for each call, won't it loop through 5-6 times at the worst case? iii. Also i am creating more strings in stringpool.

Which one should i prefer?

like image 383
Poonguzhali Gunalan Avatar asked Dec 25 '22 13:12

Poonguzhali Gunalan


2 Answers

The only way to retrieve a value from a HashMap without iterating over the entries/keys (which you don't want) is by searching for the full key.

If you require efficient search via a partial key, you should consider having a HashMap whose key is that partial key.

like image 79
Eran Avatar answered Jan 02 '23 02:01

Eran


No, it's not possible to use partial keys with a HashMap.

With TreeMap this can be achieved with a partial prefix of the wanted key, as it allows you to use tailMap(String key) to return a part of the map that would follow a specific key (i.e. your keypart). You'd still need to process the entries to see which ones would match the partial key.

like image 42
Kayaman Avatar answered Jan 02 '23 00:01

Kayaman