Answer
Iterating a HashMap in Java
Sample Data
Java
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);
scores.put("Diana", 88);
Method 1: entrySet() — Most Common and Efficient
Java
// Access both key and value in each iteration
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " → " + entry.getValue());
}
// Alice → 95
// Bob → 87
// Charlie → 92
Method 2: keySet() — When You Only Need Keys
Java
for (String name : scores.keySet()) {
System.out.println("Key: " + name);
// To get value: scores.get(name) — extra lookup
}
Method 3: values() — When You Only Need Values
Java
for (int score : scores.values()) {
System.out.println("Score: " + score);
}
// Sum all values
int total = scores.values().stream().mapToInt(Integer::intValue).sum();
System.out.println("Total: " + total); // 362
Method 4: Java 8 forEach with Lambda (Most Readable)
Java
scores.forEach((name, score) ->
System.out.println(name + " scored " + score));
// With condition
scores.forEach((name, score) -> {
if (score >= 90) {
System.out.println(name + " gets A grade");
}
});
Method 5: Iterator (When You Need to Remove During Iteration)
Java
Iterator<Map.Entry<String, Integer>> iterator = scores.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
if (entry.getValue() < 90) {
iterator.remove(); // ✅ Safe removal during iteration
// scores.remove(entry.getKey()); // ❌ ConcurrentModificationException!
}
}
System.out.println(scores); // Only Alice and Charlie remain
Method 6: Java 8 Streams
Java
// Filter and collect
Map<String, Integer> highScorers = scores.entrySet().stream()
.filter(e -> e.getValue() >= 90)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(highScorers); // {Alice=95, Charlie=92}
// Sort by value
scores.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
// Alice: 95, Charlie: 92, Diana: 88, Bob: 87
Performance Comparison
| Method | Use When |
|---|---|
entrySet() | Need both key and value (most common) |
keySet() | Only need keys |
values() | Only need values |
forEach | Cleaner code, Java 8+ |
Iterator | Need to remove elements safely |
streams | Complex filtering/transformation |
In Automation Testing
Java
// Verify test configuration from map
Map<String, String> testConfig = loadConfig();
testConfig.forEach((key, value) ->
System.out.println("Config: " + key + " = " + value));
// Check all required config keys are present
Map<String, String> required = new LinkedHashMap<>();
required.put("browser", "chrome");
required.put("baseUrl", "https://qa.example.com");
required.put("timeout", "30");
required.forEach((key, defaultVal) -> {
String actual = testConfig.getOrDefault(key, defaultVal);
System.out.println("Using " + key + ": " + actual);
});
