Optimal check and get value from hashmap

Viewed 38

I have a hashmap with a large amount of value. I want to check if it has key Id(from a list) and if it does then execute a method on it. Should I do it like this:

for (int id : myList) {
    if (myHashMap.containsKey(id)) {
         myHashMap.get(id).methodOnObject();
    }
}

Or like this:

for (int id : myList) {
    myObject temp =  myHashMap.get(id);
    if (temp != null) {
        temp.methodOnObject();
    }
}

Or something else better?

1 Answers

The second one is much better. You only query the HashMap for each key one. Theoretically, the time complexity of getting from the HashMap is constant. However, it depends on the distribution of keys and the implementation of the HashMap. It might become LogN in some cases.

Related