Java Language Java Pitfalls - Performance Issues Pitfall - Iterating a Map's keys can be inefficient


Example

The following example code is slower than it needs to be :

Map<String, String> map = new HashMap<>(); 
for (String key : map.keySet()) {
    String value = map.get(key);
    // Do something with key and value
}

That is because it requires a map lookup (the get() method) for each key in the map. This lookup may not be efficient (in a HashMap, it entails calling hashCode on the key, then looking up the correct bucket in internal data structures, and sometimes even calling equals). On a large map, this may not be a trivial overhead.

The correct way of avoiding this is to iterate on the map's entries, which is detailed in the Collections topic