Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Map Iteration Patterns

Tech 1

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);
    }
});

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.