java · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Loop over a map's keys, or over each key and value together.
visits every key, and ages.get(name) fetches its value. To get both at once, loop over ages.entrySet(). Each is a Map.Entry, with getKey() and getValue() to read its two halves.
A HashMap keeps its keys in a jumbled order that suits Java, not you. Want them sorted? Use a instead. It works the same way, but always keeps its keys in order, so loops visit them A to Z.
new TreeMap<>(ages) makes a sorted copy of any map.
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> ages = new TreeMap<>();
ages.put("Zoe", 7);
ages.put("Ava", 9);
ages.put("Leo", 11);
for (String name : ages.keySet()) {
System.out.println(name + " is " + ages.get(name));
}
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
} Printing a whole map shows it in curly brackets, like {Ava=9, Leo=11}.
guess first
Add up the goals, team by team. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> goals = new TreeMap<>();
goals.put("Robins", 2);
goals.put("Badgers", 3);
goals.put("Otters", 1);
int total = 0;
for (Map.Entry<String, Integer> team : goals.entrySet()) {
total = total + team.getValue();
System.out.println(team.getKey() + " " + total);
}
}
}
your turn
Your turn. Print the cafe menu.
Add two items and their prices in pence on lines 6 and 7. Then press run to see the menu in A to Z order.
output
press run to see what happens
fix it
The loop cannot walk through the pets. Fix it!
output
press run to see what happens
- Java says
for-each not applicable to expression typeon line 7. Can a loop walk through a map itself? - A map is not a list. Ask it for its keys first, then loop over those.
- Change
petstopets.keySet()after the colon on line 7, then press run.
nailed it
you walked through a whole map. :D
.keySet()gives every key to loop over..entrySet()gives each key and value together.- A
TreeMapkeeps its keys sorted, and aHashMapdoes not.
new words in your collection
- keySet
- entry
- TreeMap
This lesson isn’t saved. A free account remembers every lesson you finish.