Sub topic 13
Walking Through a Map
A map stores pairs. Each pair has a key and a value. To work through every pair, you use a loop. A map has no index like a list, so you can't count from 0 to size(). Instead, the map gives you three views of its contents. A view is a collection that looks into the map without copying it.
The Three Views
| Method | What it returns | Use it when |
|---|---|---|
| `entrySet()` | A `Set` of `Map.Entry` objects, one per pair | You need both the key and the value |
| `keySet()` | A `Set` of the keys | You only need the keys |
| `values()` | A `Collection` of the values | You only need the values |
A Map.Entry is a small object that holds one key and its value. You read them with getKey() and getValue().
A Worked Example
This program tracks fruit in a shop. It uses a TreeMap, a map that keeps its keys in sorted order. The sorted order means the output is the same every time you run it. A later chapter covers TreeMap in detail.
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]
int total = 0;
for (int count : stock.values()) {
total += count;
}
System.out.println(total); // 21
}
}Here is what each part does:
- The
forloop overentrySet()gives you one entry per pair. You get the key and the value together. keySet()prints just the fruit names.values()prints just the counts. The last loop adds them up.
Why entrySet Is Usually Best
Beginners often write this:
for (String fruit : stock.keySet()) {
System.out.println(fruit + " = " + stock.get(fruit));
}It works, but it does extra work. For every key, get has to look up that key in the map again. entrySet() already hands you the value, so no second lookup is needed. If you need both parts, use entrySet().
Order Depends on the Map
The order you see depends on the kind of map:
HashMapgives no promised order. The order can look random and can change as the map grows.TreeMapgives keys in sorted order.LinkedHashMapgives keys in the order you inserted them.
Don't write code that depends on a HashMap returning pairs in a certain order.
Exercise
You have a Map<String, Integer> called scores. Write a loop that prints only the names of people whose score is above 50, using a single lookup per pair.
Show answer
Loop over entrySet so each pair is read once: for (Map.Entry<String, Integer> e : scores.entrySet()) { if (e.getValue() > 50) { System.out.println(e.getKey()); } }
Exercise
Which view would you use to find the largest value in a map, and why?
Show answer
Use values(), because you only need the values and not the keys. For example: int max = Integer.MIN_VALUE; for (int v : map.values()) { max = Math.max(max, v); }