Java Map Iteration Patterns
Iterating over Map implementations requires selecting appropriate strategies based on whether you need keys, values, or both, alongside considerations for concurrent modification and Java version compatibility.
Entry-Based Traversal
Accessing both keys and values simultaneously through entrySet() offers optimal performance by avoiding repeated hash loookups:
Map<Long, String> sessionCache = new HashMap<>();
sessionCache.put(1001L, "Active");
sessionCache.put(1002L, "Pending");
sessionCache.put(1003L, "Closed");
for (Map.Entry<Long, String> record : sessionCache.entrySet()) {
Long sessionId = record.getKey();
String status = record.getValue();
System.out.printf("Session %d: %s%n", sessionId, status);
}
Key or Value Isolation
When only identifiers or data elements are required, iterate over specific collections:
// Process only keys
for (Long id : sessionCache.keySet()) {
auditLog.append("Scanned ID: ").append(id).append("\n");
}
// Aggregate values
for (String state : sessionCache.values()) {
if ("Active".equals(state)) {
activeCounter.increment();
}
}
Iterator-Based Navigation
Explicit Iterator instances enable safe element removal during traversal:
Iterator<Map.Entry<Long, String>> cursor = sessionCache.entrySet().iterator();
while (cursor.hasNext()) {
Map.Entry<Long, String> entry = cursor.next();
if ("Closed".equals(entry.getValue())) {
cursor.remove(); // Safe deletion
}
}
Functional Approach (Java 8+)
Lambda expressions provide concise syntax for read-only operations:
sessionCache.forEach((id, status) -> {
if (status.startsWith("A")) {
notificationService.alert(id);
}
});