java · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put a new value under an old key and the old one is gone.
A key holds one value at a time, so .put on a key that is already there replaces its value. .remove("pears") takes the whole pair out, and tells you whether a key is there.
gives the value under kiwis, or 0 if there is none. No more null surprises.
Together they make a . For each vote, read the old count with getOrDefault, add one and put it back: votes.put(pet, votes.getOrDefault(pet, 0) + 1);.
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] ballots = {"cat", "dog", "cat", "rabbit", "cat"};
HashMap<String, Integer> votes = new HashMap<>();
for (String pet : ballots) {
votes.put(pet, votes.getOrDefault(pet, 0) + 1);
}
System.out.println("cat: " + votes.get("cat"));
System.out.println("dog: " + votes.get("dog"));
System.out.println("hamster: " + votes.getOrDefault("hamster", 0));
System.out.println(votes.containsKey("rabbit"));
}
} .put never complains about a new key, so a typo can quietly start a second count.
guess first
The scores keep changing. 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) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Ava", 10);
scores.put("Leo", 8);
scores.put("Ava", 15);
scores.remove("Leo");
System.out.println(scores.size() + " " + scores.get("Ava"));
}
}
your turn
Your turn. Count the drinks order.
Add two drinks of your choice on line 4. On line 7, fill in the map method that gives a backup value when a key is missing. Then press run.
output
press run to see what happens
fix it
The bird count is stuck on 1. Can you fix it?
output
press run to see what happens
- Robins were seen three times, but the count says 1. What does line 7 do on each turn?
.putreplaces the old value, so every sighting resets the count to 1. Read the old count first.- Change line 7 to
birds.put(bird, birds.getOrDefault(bird, 0) + 1);, then press run.
nailed it
you kept a tally with a map. :D
.puton an old key replaces its value..getOrDefaultgives a backup value for a missing key.- To tally, read the count, add one and put it back.
new words in your collection
- containsKey
- getOrDefault
- tally
This lesson isn’t saved. A free account remembers every lesson you finish.