×

java · level 2 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.