Task 5 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.1 HashMap — iterating over entries

Lesson

Visiting every pair

To process a whole map, loop over its keys with keySet() (an enhanced for loop works well), and use get(key) to reach each value. Note: a HashMap has no guaranteed order — never rely on the keys coming out in any particular sequence. Order-independent totals like a sum are safe.


Worked example

Map<String, Integer> ages = new HashMap<String, Integer>();
ages.put("Ada", 30);
ages.put("Sam", 25);

int total = 0;
for (String key : ages.keySet()) {   // visit each key
    total = total + ages.get(key);    // add its value
}
System.out.println(total);   // 55

The sum is the same no matter what order the keys are visited in.


▶ Try it: run this — it adds up every value in the map.



keySet() gives you...


The order in which a HashMap's keys are visited is...


Type exactly what this program prints.

import java.util.HashMap;
import java.util.Map;
public class Main { public static void main(String[] a){
    Map<String, Integer> m = new HashMap<String, Integer>();
    m.put("a", 3);
    m.put("b", 4);
    m.put("c", 5);
    int t = 0;
    for (String k : m.keySet()) { t = t + m.get(k); }
    System.out.println(t);
}}

Inside the loop, you reach each value with...


True or false?