I am comparing 2 HashMaps, and I am trying to figure out the time complexity of the comparison loop.
The code is as follows:
//map1 is a HashMap and contains m elements and keys
//map2 is a HashMap and contains n elements and keys
List<myObject> myList = new ArrayList<myObject>()
for (String key: map1.keySet()){
if(!map2.containsKey(key)){
myList.add(map.get(key));
}
}
The first for loop will be O(m). I found on some other forum that the containsKey() takes lg(n) time. Can someone please confirm that? I couldn’t find it in the JavaDocs.
If so , then the the total time complexity would be O(mlg{n}).
Also any ideas on how to do this comparison in a better way would be helpful.
Depends on your hashcode algorithm and collisions.
Using a perfect hashcode, theoretically map look up is O(1), constant time, if there are collisions, it might be upto O(n).
So in your case, if you have good hash algorithms, it would be O(m).
if you look at wiki, you can get more understanding about the concept. You can also look at Map source code.