5 Efficient Ways to Iterate Over a Java Map (with Code Samples)
This tutorial explains five different techniques for traversing Java Map collections—including keySet, entrySet, for‑each loops, and lambda forEach—provides complete code examples for each method, shows the resulting output, and offers performance recommendations.
In Java all map implementations implement the Map interface, so any Map can be traversed using several approaches. This article presents five ways to iterate over a Map collection, each illustrated with full example code and its output.
Method 1: Iterate with Map.keySet() and an Iterator
@Test
public void testHashMap1() {
Map<Integer, String> map = new HashMap<>();
map.put(001, "Java");
map.put(002, "数据库");
map.put(003, "Vue");
System.out.println(map);
// Iterate keys, then get values
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
String value = map.get(key);
System.out.println("key = " + key + ", value = " + value);
}
}Result:
{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = VueMethod 2: Iterate with Map.entrySet() and an Iterator
@Test
public void testHashMap2() {
Map<Integer, String> map = new HashMap<>();
map.put(001, "Java");
map.put(002, "数据库");
map.put(003, "Vue");
System.out.println(map);
// Iterate key‑value pairs directly
Iterator<Map.Entry<Integer, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, String> entry = entries.next();
System.out.println(entry);
}
}Result:
{1=Java, 2=数据库, 3=Vue}
1=Java
2=数据库
3=VueMethod 3: Iterate with enhanced for over keySet()
@Test
public void testHashMap3() {
Map<Integer, String> map = new HashMap<>();
map.put(001, "Java");
map.put(002, "数据库");
map.put(003, "Vue");
System.out.println(map);
// Iterate keys using for‑each
for (Integer key : map.keySet()) {
System.out.println("key = " + key + ", value = " + map.get(key));
}
}Result:
{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = VueMethod 4: Iterate with enhanced for over entrySet()
@Test
public void testHashMap4() {
Map<Integer, String> map = new HashMap<>();
map.put(001, "Java");
map.put(002, "数据库");
map.put(003, "Vue");
System.out.println(map);
// Iterate entries directly
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
}Result:
{1=Java, 2=数据库, 3=Vue}
key = 1, value = Java
key = 2, value = 数据库
key = 3, value = VueMethod 5: Iterate with Map.forEach lambda (JDK 8+)
@Test
public void testHashMap5() {
Map<Integer, String> map = new HashMap<>();
map.put(001, "Java");
map.put(002, "数据库");
map.put(003, "Vue");
System.out.println(map);
// Lambda‑based forEach
map.forEach((k, v) -> System.out.println("key = " + k + ", value = " + v));
}Source of forEach (from JDK 8):
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}From the source it is clear that this new feature adds a thin wrapper around the traditional iteration, making the code much simpler; it is recommended for production use.
Conclusion
It is recommended to use entrySet() (Method 4) for traversing a Map because it iterates only once and provides both key and value directly, offering better performance than the keySet() approach, which requires a second lookup for each value. For JDK 8 and later, the lambda‑based Map.forEach (Method 5) is also highly convenient.
Additional notes: keySet() iterates twice – first to obtain an Iterator, then to fetch each value from the map. entrySet() iterates once, exposing both key and value in each entry. values() returns a collection of values, keySet() returns a set of keys, and entrySet() returns a set of key‑value pairs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Huawei Cloud Developer Alliance
The Huawei Cloud Developer Alliance creates a tech sharing platform for developers and partners, gathering Huawei Cloud product knowledge, event updates, expert talks, and more. Together we continuously innovate to build the cloud foundation of an intelligent world.
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.
