Sub topic 13
Walking Through a Map
A map stores pairs. Each pair has a key (the thing you look up by) and a value (the thing you get back). In the last chapter you used put, get, and merge to work with one key at a time. This chapter shows how to visit every pair in a map, one after another. Visiting each item in turn is called iterating.
You will learn three ways to look at a map's contents, how to change values while you loop, and how to remove pairs without crashing your program.
Why a Map Needs a Different Approach
A List or a Set holds single elements, so a for-each loop can hand you one element per step. A map holds pairs, so it is not clear what one "step" should give you. It could be the key, the value, or both.
Java solves this by not letting you loop over a map directly. The Map interface does not extend Iterable, which is the interface that for-each loops need. This line does not compile:
// for (String s : stock) { } // compile error: Map is not IterableInstead, a map gives you views. A view is a collection that shows the map's data in a certain shape. It does not copy the data. There are three views:
| Method | What it returns | Type of each element | Use it when you need |
|---|---|---|---|
| `keySet()` | A `Set` of all keys | `K` (the key type) | Only the keys |
| `values()` | A `Collection` of all values | `V` (the value type) | Only the values |
| `entrySet()` | A `Set` of all pairs | `Map.Entry<K, V>` | Keys and values together |
Map.Entry is a small interface inside Map. One entry holds one key and its value. You read them with getKey() and getValue().
Notice that keySet() returns a Set, because keys in a map are always unique. values() returns a plain Collection, because two keys can have the same value, so values may repeat.
A First Walk Through a Map
The program below fills a map with fruit stock and then walks through it in three ways.
import java.util.Map;
import java.util.TreeMap;
public class MapIterationDemo {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("pears", 4);
stock.put("apples", 10);
stock.put("oranges", 7);
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
// apples = 10
// oranges = 7
// pears = 4
System.out.println(stock.keySet()); // [apples, oranges, pears]
System.out.println(stock.values()); // [10, 7, 4]
}
}This example uses a TreeMap, which keeps its keys in sorted order, so the output is the same every time you run it. A chapter later in this tutorial covers TreeMap in detail.
Read the loop header slowly:
Map.Entry<String, Integer>is the type of each item. The key is aStringand the value is anInteger, matching the map.eis the name of the current entry.stock.entrySet()is the view you loop over.
Choosing the Right View
Only the keys: keySet
Use keySet() when you only care about the keys, for example to print every name in a phone book.
for (String fruit : stock.keySet()) {
System.out.println(fruit);
}Only the values: values
Use values() when you only care about the values. A common job is adding them up:
int total = 0;
for (int count : stock.values()) {
total += count;
}
System.out.println(total); // 21Here each Integer is unboxed to an int automatically, as you saw in the autoboxing chapter.
Both: entrySet
Use entrySet() when you need both the key and the value. Beginners often write this instead:
for (String fruit : stock.keySet()) {
System.out.println(fruit + " = " + stock.get(fruit)); // works, but does extra work
}This code gives the right answer, but it looks up every key twice: once while looping and again inside get. With entrySet(), the key and value arrive together, so no second lookup happens. The entry version is also easier to read, so prefer it.
A shortcut: forEach with a lambda
Since Java 8, every map has a forEach method. You pass it a lambda, a short block of code with parameters. For a map, the lambda takes two parameters, the key and the value:
stock.forEach((fruit, count) -> System.out.println(fruit + ": " + count));This does the same job as the entrySet() loop in one line.
Changing a Map While You Walk Through It
Because views are live windows onto the map, changes made through a view change the map itself. This is useful, but you have to use the right tools.
The program below removes sold-out fruit, raises every count, and then removes one key through the key view.
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class MapUpdateDemo {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("apples", 10);
stock.put("oranges", 7);
stock.put("pears", 4);
stock.put("plums", 0);
stock.put("figs", 0);
// 1. Remove every pair whose value is 0
stock.entrySet().removeIf(e -> e.getValue() == 0);
System.out.println(stock); // {apples=10, oranges=7, pears=4}
// 2. Add 5 to every value, in place
for (Map.Entry<String, Integer> e : stock.entrySet()) {
e.setValue(e.getValue() + 5);
}
System.out.println(stock); // {apples=15, oranges=12, pears=9}
// 3. Remove with an explicit Iterator
Iterator<Map.Entry<String, Integer>> it = stock.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> e = it.next();
if (e.getValue() < 10) {
it.remove();
}
}
System.out.println(stock); // {apples=15, oranges=12}
// 4. Removing from a view removes from the map
stock.keySet().remove("oranges");
System.out.println(stock); // {apples=15}
stock.forEach((fruit, count) -> System.out.println(fruit + ": " + count));
// apples: 15
}
}Each step works like this:
removeIfon the entry view deletes every pair that matches the test. It is the shortest safe way to remove pairs.setValuechanges the value of the current entry. It is safe inside a for-each loop because it does not add or remove keys.Iterator.remove()deletes the pair thatnext()just returned. Use this when your removal logic is too long for a lambda.- Removing a key from
keySet()removes the whole pair from the map. The view and the map share the same data.
Edge Cases Worth Knowing
- Empty map: looping over any view of an empty map simply runs zero times. No error occurs.
- Repeated values:
values()may contain the same value more than once. If you need each value only once, copy it into a set:new HashSet<>(map.values()). - Removing by value:
map.values().remove(4)removes only the first pair it finds with value 4. To remove all of them, usemap.values().removeIf(v -> v == 4). - Adding through a view: you cannot add to
keySet()orvalues(). Callingaddon them throwsUnsupportedOperationException, because a key without a value (or a value without a key) makes no sense. Useputon the map. - null values: a
HashMapallowsnullvalues. If you unbox anullvalue into anint(for example,int c = e.getValue();), you get aNullPointerException.
Summary
- A map is not directly iterable. You loop over one of its three views.
- Use
keySet()for keys,values()for values, andentrySet()orforEachfor both. - Views are live. Changes through them affect the map.
- To remove pairs while looping, use
removeIforIterator.remove(). To change values, usesetValue.
Exercise
You have a Map<String, Integer> called scores that maps player names to points. Write a loop that prints each line as "name has N points", without looking up any key twice.
Show answer
Loop over the entry view: for (Map.Entry<String, Integer> e : scores.entrySet()) { System.out.println(e.getKey() + " has " + e.getValue() + " points"); } A one-line version also works: scores.forEach((name, pts) -> System.out.println(name + " has " + pts + " points"));
Exercise
A classmate writes for (String name : scores.keySet()) { if (scores.get(name) < 0) { scores.remove(name); } } and the program sometimes crashes. Why, and what is a safe one-line fix?
Show answer
Calling scores.remove inside a for-each loop over a view changes the map's keys during iteration, which can throw ConcurrentModificationException. A safe fix is scores.entrySet().removeIf(e -> e.getValue() < 0); (or scores.values().removeIf(v -> v < 0);).
Exercise
Given Map<String, Integer> prices, write code that doubles every price in place, then computes the total of all prices.
Show answer
for (Map.Entry<String, Integer> e : prices.entrySet()) { e.setValue(e.getValue() * 2); } Then: int total = 0; for (int p : prices.values()) { total += p; } Using setValue is safe during the loop because it does not add or remove keys.