Understanding HashMap Traversal: keySet vs entrySet and Iterator Mechanics
This article explains the various ways to traverse a Java HashMap, compares keySet and entrySet approaches, shows why keySet involves two passes, and demonstrates the underlying iterator implementation with detailed code examples and decompiled snippets.
HashMap is a widely used Java container, and its traversal methods are essential knowledge for developers. The article lists the common traversal techniques: using an Iterator, using keySet() with an enhanced for‑loop, using entrySet() with an enhanced for‑loop, and using Java 8+ lambda and streams.
The Alibaba Development Manual recommends entrySet for iteration and, in Java 8, suggests Map.forEach() because it reduces the number of traversals.
It explains that keySet traversal actually performs two passes: one to obtain an iterator over the key set and another to retrieve each value from the map. In contrast, entrySet traversal accesses key‑value pairs directly in a single pass.
Code examples illustrate a simple keySet loop:
public class Test {
public static void main(String[] args) {
Map
map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println(key + ":" + value);
}
}
}The compiled bytecode (shown via decompilation) reveals that the enhanced for‑loop is transformed into an explicit iterator call:
public class Test {
public static void main(String[] args) {
Map
map = new HashMap();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
Iterator var2 = map.keySet().iterator();
while (var2.hasNext()) {
String key = (String) var2.next();
String value = (String) map.get(key);
System.out.println(key + ":" + value);
}
}
}The KeySet class implements iterator() by returning a new KeyIterator , which extends the abstract HashIterator . The HashIterator constructor contains a do‑while loop that advances to the first non‑null entry in the internal table, effectively performing the first traversal.
Key points summarized:
Using keySet internally relies on the iterator() method.
The iterator() method creates a KeyIterator object.
KeyIterator extends HashIterator .
HashIterator 's constructor iterates to locate the first non‑empty entry.
Thus, the traversal chain is: keySet → iterator() → KeyIterator → HashIterator .
At the end, the article includes promotional material for a free programming book, but the technical explanation remains the core content.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.