Skip to lesson

Looping through a map

A map has no index, so you cannot loop over it with i = 0, 1, 2…. Instead, a map gives you three views: its keys, its values and its entries. You loop over a view with a normal for-each loop.

Three views of a map

A view is a live window onto a map, not a copy. keySet(), values() and entrySet() are views: if the map changes, the view shows it, and removing through a view removes from the map too.

A map has no index, so you cannot loop with i = 0, 1, 2. Instead you loop over one of its views. Below, keySet() lists the students and values() adds up their attendance days.

Example 1 · keySet and values

AttendanceDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class AttendanceDemo {    public static void main(String[] args) {        Map<String, Integer> daysPresent = new HashMap<>();        daysPresent.put("Asha", 22);        daysPresent.put("Bala", 18);        daysPresent.put("Chitra", 24);        daysPresent.put("Dev", 20);
        System.out.print("Students:");        for (String name : daysPresent.keySet()) {            System.out.print(" " + name);        }        System.out.println();
        int total = 0;        for (int days : daysPresent.values()) {            total += days;        }        System.out.println("Total days: " + total);        System.out.println("Average: " + (double) total / daysPresent.size());    }}
Output
Students: Chitra Asha Dev Bala
Total days: 84
Average: 21.0

What this code does

  • keySet() is a Set<String>, so a for-each loop gives one name at a time. The names come in the map's own order, which is not promised.
  • values() gives only the numbers, which is all we need for a total. Each Integer is unboxed into int days.

keySet() gives a Set<K> of all keys. values() gives a Collection<V>, not a Set, because values may repeat. entrySet() gives a Set<Map.Entry<K, V>>, used when you need the key and the value together.

A HashMap loops in no promised order. To loop in sorted key order, loop over new TreeSet<>(map.keySet()).

Map.Entry: key and value together

Map.Entry is a small interface inside Map. Each entry object holds one key and its value: getKey() and getValue() read them, and setValue(newValue) changes the value in the map itself.

Looping over keySet() and calling get for each key looks up every key twice. entrySet() hands you the key and the value together. Below, one loop finds the student with the highest fee due.

Example 2 · entrySet: key and value together

FeeDuesDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class FeeDuesDemo {    public static void main(String[] args) {        Map<String, Integer> dues = new HashMap<>();        dues.put("Riya", 2000);        dues.put("Arjun", 0);        dues.put("Meera", 7500);        dues.put("Kabir", 3200);
        Map.Entry<String, Integer> highest = null;        int pending = 0;
        for (Map.Entry<String, Integer> e : dues.entrySet()) {            if (e.getValue() > 0) {                pending++;            }            if (highest == null || e.getValue() > highest.getValue()) {                highest = e;            }        }
        System.out.println("Students with dues: " + pending);        System.out.println("Highest due: " + highest.getKey() + ", Rs. " + highest.getValue());    }}
Output
Students with dues: 3
Highest due: Meera, Rs. 7500

What this code does

  • Each e holds one name and its due, so no second lookup with get is needed.
  • A whole entry can be kept in a variable. highest remembers the best entry seen so far, with both its key and value.

Each e holds one name and its due, so no second lookup is needed. entrySet() is the usual choice whenever the loop needs both the key and the value.

forEach with a lambda

A local variable is effectively final if it is never changed after it is set. A lambda may use only such variables, so total += r inside forEach does not compile.

map.forEach((key, value) -> ...) runs a lambda once for every entry. Below, one scorecard is printed in map order and in sorted order; the next example breaks the lambda rule on purpose.

Example 3 · forEach, and looping in sorted order

ScorecardDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;
public class ScorecardDemo {    public static void main(String[] args) {        Map<String, Integer> runs = new HashMap<>();        runs.put("Rohit", 45);        runs.put("Gill", 72);        runs.put("Virat", 8);        runs.put("Pant", 31);
        System.out.println("-- map order --");        runs.forEach((batter, r) -> System.out.println(batter + ": " + r));
        System.out.println("-- name order --");        for (String batter : new TreeSet<>(runs.keySet())) {            System.out.println(batter + ": " + runs.get(batter));        }    }}
Output
-- map order --
Rohit: 45
Pant: 31
Gill: 72
Virat: 8
-- name order --
Gill: 72
Pant: 31
Rohit: 45
Virat: 8

What this code does

  • forEach takes a lambda with two parameters, the key and the value, and runs it for every entry.
  • The first block uses the HashMap's order, which is not promised. The second copies the keys into a TreeSet, which keeps them sorted, and loops over that.

Example 4 · Mistake: changing a local variable inside forEach

LambdaTotalDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class LambdaTotalDemo {    public static void main(String[] args) {        Map<String, Integer> runs = new HashMap<>();        runs.put("Rohit", 45);        runs.put("Gill", 72);
        int total = 0;        runs.forEach((batter, r) -> total += r);        System.out.println("Team total: " + total);    }}
Sample compiler output
LambdaTotalDemo.java:11: error: local variables referenced from a lambda expression must be final or effectively final
        runs.forEach((batter, r) -> total += r);
                                    ^
1 error

What this code does

  • A lambda may read a local variable only if it never changes. total += r tries to change total, so the compiler stops.
  • The fix is a normal loop: for (int r : runs.values()) { total += r; }.

The lambda takes two parameters: the key and the value. It is short and clear for printing or calling a method on each entry. To add things up, use a for-each loop over values() instead.

Fix the error

Fix the loop over a map

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Add up the runs of a team.

int total = 0;
runsMap.forEach((batter, r) -> total += r);
System.out.println(total);

Error

Main.java:7: error: local variables referenced from a lambda expression must be final or effectively final
        runsMap.forEach((batter, r) -> total += r);
                                       ^

Removing while you loop

Concurrent modification means a collection is changed while a loop is still reading it. A for-each loop over a map view notices and throws a ConcurrentModificationException.

If you call map.remove(key) inside a for-each loop over the same map, the loop's hidden iterator notices the change and throws. Below is the crash, then the safe fix with setValue and removeIf.

Example 5 · Mistake: removing inside a for-each loop

RemoveCrashDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class RemoveCrashDemo {    public static void main(String[] args) {        Map<String, Integer> marks = new HashMap<>();        marks.put("Asha", 78);        marks.put("Bala", 28);        marks.put("Chitra", 91);        marks.put("Dev", 33);
        for (String name : marks.keySet()) {            if (marks.get(name) < 35) {                marks.remove(name);            }        }        System.out.println(marks);    }}
Sample output
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1605)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1628)
	at RemoveCrashDemo.main(RemoveCrashDemo.java:12)

What this code does

  • marks.remove(name) changes the map while the for-each loop's iterator is still walking over it.
  • On its next step the iterator sees the change and throws ConcurrentModificationException.

Example 6 · The fix: setValue and removeIf

GraceMarksDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;
public class GraceMarksDemo {    public static void main(String[] args) {        Map<String, Integer> marks = new HashMap<>();        marks.put("Asha", 78);        marks.put("Bala", 28);        marks.put("Chitra", 91);        marks.put("Dev", 33);        marks.put("Esha", 30);
        // Grace marks: 30 to 34 gets 5 more        for (Map.Entry<String, Integer> e : marks.entrySet()) {            int m = e.getValue();            if (m >= 30 && m < 35) {                e.setValue(m + 5);            }        }
        // Remove everyone still below 35        marks.values().removeIf(m -> m < 35);
        for (String name : new TreeSet<>(marks.keySet())) {            System.out.println(name + " passed with " + marks.get(name));        }    }}
Output
Asha passed with 78
Chitra passed with 91
Dev passed with 38
Esha passed with 35

What this code does

  • setValue changes the value inside the map while looping. It is safe, because no entry is added or removed.
  • values().removeIf(…) removes every entry whose value matches. Removing through a view removes from the map itself.
  • The final loop goes through the keys in sorted order, so the output order is fixed.

removeIf on a view removes every match for you: map.values().removeIf(m -> m < 35), or map.entrySet().removeIf(e -> ...) when the test needs the key. Or loop with an explicit Iterator and call it.remove().

Find the bug

Find the unsafe removal

Each snippet throws an exception at run time. Tap the wrong line, then check the fix.

Remove every student with marks below 35.

Round 1 of 2
Changing the value of an existing key while looping is safe. Use entry.setValue(...); it does not add or remove entries.

Next step

Check your understanding

12 quick questions