Map.Entry and Iterating Over Maps
Map.Entry in Java is a nested interface of Map that represents one key-value pair. When you loop over a map's entrySet(), each item you get is a Map.Entry, from which you can read the key and the value together. In this lesson, you will learn the methods of Map.Entry and all the common ways to iterate over a map, including how to remove entries safely during a loop.
Declaration
interface Map<K, V> {
interface Entry<K, V> { ... }
}Methods of Map.Entry
| Method | Description |
|---|---|
K getKey() | It returns the key of this pair. |
V getValue() | It returns the value of this pair. |
V setValue(V value) | It replaces the value in the map and returns the old one. |
static comparingByKey() | It returns a comparator that compares entries by key. |
static comparingByValue() | It returns a comparator that compares entries by value. |
Map.entry(k, v) (Java 9) creates a standalone, unmodifiable entry.
Ways to Iterate Over a Map
| Way | Gives you | Best for |
|---|---|---|
for (Map.Entry<K, V> e : map.entrySet()) | Key and value | Most loops; the usual choice |
for (K k : map.keySet()) | Keys only | When only keys are needed |
for (V v : map.values()) | Values only | Totals, averages |
map.forEach((k, v) -> ...) | Key and value | Short one-line actions |
Iterator over entrySet() | Key, value and safe removal | Removing while looping |
Example: Four Loops Over One Map
Let's see an example of each loop on a map of marks.
import java.util.LinkedHashMap;
import java.util.Map;
public class MapLoops {
public static void main(String[] args) {
Map<String, Integer> marks = new LinkedHashMap<>();
marks.put("Navika", 91);
marks.put("Srihitha", 78);
marks.put("Advitha", 85);
for (Map.Entry<String, Integer> e : marks.entrySet()) {
System.out.println(e.getKey() + " scored " + e.getValue());
}
for (String name : marks.keySet()) {
System.out.print(name + " ");
}
System.out.println("(keys)");
int total = 0;
for (int m : marks.values()) {
total += m;
}
System.out.println("Total: " + total);
marks.forEach((name, m) -> System.out.println(name + " -> " + m));
}
}Navika scored 91
Srihitha scored 78
Advitha scored 85
Navika Srihitha Advitha (keys)
Total: 254
Navika -> 91
Srihitha -> 78
Advitha -> 85Explanation: The entrySet loop gives both parts of each pair. The keySet loop gives names only, and the values loop adds up the marks. forEach takes a lambda with two parameters, the key and the value.
Example: Changing and Removing During a Loop
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class EntryChanges {
public static void main(String[] args) {
Map<String, Integer> marks = new LinkedHashMap<>();
marks.put("Navika", 91);
marks.put("Srihitha", 38);
marks.put("Advitha", 85);
for (Map.Entry<String, Integer> e : marks.entrySet()) {
e.setValue(e.getValue() + 5);
}
System.out.println("Grace marks: " + marks);
Iterator<Map.Entry<String, Integer>> it = marks.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue() < 50) {
it.remove();
}
}
System.out.println("Passed: " + marks);
marks.entrySet().removeIf(e -> e.getKey().startsWith("A"));
System.out.println("After removeIf: " + marks);
}
}Grace marks: {Navika=96, Srihitha=43, Advitha=90}
Passed: {Navika=96, Advitha=90}
After removeIf: {Navika=96}Explanation: setValue changes a value in place during the loop, which is allowed. Removing must go through the iterator's remove, or through removeIf; calling marks.remove(key) inside a for-each loop would throw ConcurrentModificationException.
Common Mistakes
Calling map.remove(key) inside a for-each loop over the map. Use removeIf or an iterator.
Calling map.put(newKey, ...) while iterating. Adding keys during iteration also throws; collect changes and apply them after the loop.
Using raw Map.Entry without type arguments. Write Map.Entry<String, Integer> or use var.
Practice
- Easy: Print every entry of a map of product prices as "product: price", then print the most expensive product.
- Harder: Remove every entry whose value appears more than once in the map, using only
removeIfand thevalues()view.
Key Takeaways
Was this tutorial helpful?