Jacky
Jacky

Reputation: 298

Retrieve value using key without using iterator in HashMap

I would like to retrieve value based on the key from HashMap. I am able to get the value based in the key from hashmap using below code. I have got the perfect result. I believe each time looping for a value from 1000+ records is not a good idea. It makes application much slower.

Here is the bunch of code with the for loop.

 HashMap<Integer, LabelModel> labelHashMap = gson.fromJson(storedHashMapString, type);

    for(Map.Entry<Integer, LabelModel> entry:labelHashMap.entrySet())
    {
        LabelModel label = entry.getValue();
        key = label.getKey();
        if(key != null && !key.isEmpty())
        {
            if(key.equalsIgnoreCase("please_select_governorate"))
            {
                english_label = label.getEnglish();
                arabic_label = label.getArabic();
            }
        }
    }

I do not want to make my app slower. So, I would prefer directly retrieving the value with the help of key without using iterator or for loop. How can I achieve this?

Help would be appreciated.

Upvotes: 0

Views: 1736

Answers (3)

Jake Psimos
Jake Psimos

Reputation: 640

if(labelHashMap.get("something") != null){ code }

if you attempt to get a value with a key that does not exist then the hash map will simply return null.

Upvotes: 0

Evan Jones
Evan Jones

Reputation: 886

I don't think it's possible to do directly, but you could make an initial pass over the whole map and transform it into a map that uses the sting keys as keys. At least this way you only have to iterate over the whole value set once.

So if you use a method like

Map<String, LabelModel> reIndex(HashMap<Integer, LabelModel> labelMap) {
    Map<String, LabelModel> reIndexedLabelMap = new HashMap<>();
    for(Map.Entry<Integer, LabelModel> entry:labelMap.entrySet()) {
        LabelModel label = entry.getValue();
        String key = label.getKey();
        reIndexedLabelMap.put(key.toLowerCase(), label); 
    }
    return reIndexedLabelMap; 
}

You can then use this new object to quickly grab any other label by it's String key:

Map<String, LabelModel> reIndexed = reIndex(labeHashlMap);
reIndexed.get("please_select_governorate");
reIndexed.get("what_ever_else");

Assuming that the keys are unique with respect to case.

Upvotes: 1

avinash gupta
avinash gupta

Reputation: 11

I think you should do an initial pass i.e iterating over JSON. because mapping from JSON to HashMap is iterative as well, which you can avoid.

Upvotes: 0

Related Questions