Map.Entry and Iterating Over Maps

Naveen AnamaneniUpdated · 4 min read

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

Declaration
interface Map<K, V> {
    interface Entry<K, V> { ... }
}

Methods of Map.Entry

MethodDescription
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

WayGives youBest for
for (Map.Entry<K, V> e : map.entrySet())Key and valueMost loops; the usual choice
for (K k : map.keySet())Keys onlyWhen only keys are needed
for (V v : map.values())Values onlyTotals, averages
map.forEach((k, v) -> ...)Key and valueShort one-line actions
Iterator over entrySet()Key, value and safe removalRemoving while looping

Example: Four Loops Over One Map

Let's see an example of each loop on a map of marks.

MapLoops.java▶ Try it
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));
    }
}
Output
Navika scored 91
Srihitha scored 78
Advitha scored 85
Navika Srihitha Advitha (keys)
Total: 254
Navika -> 91
Srihitha -> 78
Advitha -> 85

Explanation: 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

EntryChanges.java▶ Try it
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);
    }
}
Output
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

  1. Easy: Print every entry of a map of product prices as "product: price", then print the most expensive product.
  2. Harder: Remove every entry whose value appears more than once in the map, using only removeIf and the values() view.

Quick check: Map.Entry

4 questions
1What does a Map.Entry represent?
2Which loop gives both keys and values without extra lookups?
3How can you safely remove entries while looping?
4Which method changes a value during iteration?

Key Takeaways

Was this tutorial helpful?

Lesson 281 of 482