简体   繁体   English

在HashMap中使用键检索值而不使用迭代器

[英]Retrieve value using key without using iterator in HashMap

I would like to retrieve value based on the key from HashMap . 我想基于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. 我认为每次循环获取1000多个记录中的值都不是一个好主意。 It makes application much slower. 这会使应用程序变慢。

Here is the bunch of code with the for loop. 这是带有for循环的一堆代码。

 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. 因此,我宁愿直接在键的帮助下检索值,而无需使用迭代器或for循环。 How can I achieve this? 我该如何实现?

Help would be appreciated. 帮助将不胜感激。

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: 然后,您可以使用此新对象通过其String键快速获取其他标签:

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. 假定键相对于大小写是唯一的。

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

如果尝试使用不存在的键获取值,则哈希映射将仅返回null。

I think you should do an initial pass ie iterating over JSON. 我认为您应该进行初始遍历,即遍历JSON。 because mapping from JSON to HashMap is iterative as well, which you can avoid. 因为从JSON到HashMap的映射也是迭代的,所以可以避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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