Pitfall - Iterating a Maps keys can be inefficient

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalss - performance:
* Pitfall - Iterating a Maps keys can be inefficient

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
112 Pitfalss - performance
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap