Walk a sequence and count occurrences of each value in a hash map. Classic "get current count, add one, write back" loop.

Algorithm

Basic Implementation

Basic.java
import java.util.HashMap;
import java.util.Map;

public class Basic {
    public static void main(String[] args) {
        String[] words = {"fig", "apple", "fig", "pear", "apple", "fig"};
        Map<String, Integer> count = new HashMap<>();
        for (String word : words) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }
        System.out.println(count);
    }
}

The pinned input is [fig, apple, fig, pear, apple, fig]. The diagrams show get-or-default, writeback, and final bucket contents.

Step 1 - First write creates a key

fig is absent, so get-or-default reads 0 and writes fig: 1.

After reading the first word fig.wordold countnew countmapfig01{fig: 1}

Step 2 - Existing keys increment

The second fig reads 1 and writes 2; apple has its own count.

After fig, apple, fig.scanfigapplepearafter fig100after apple110after fig210

Step 3 - Final counts

The full scan produces fig: 3, apple: 2, and pear: 1.

Final map for [fig, apple, fig, pear, apple, fig].bucket/keycountfig3apple2pear1

Complexity

  • Time: O(n) average
  • Space: O(k) where k is the number of distinct keys

Implementation notes

  • Java: Map<String, Integer> count = new HashMap<>(); with count.put(word, count.getOrDefault(word, 0) + 1). The count.merge(word, 1, Integer::sum) form is equally idiomatic but hides the read; the explicit form is used here so the lesson stays about the get-then-write idea.
  • The replay renders the map as a list of key/value rows and animates the count increment on each frame.
get-or-default `count.getOrDefault(word, 0)` returns the current count or `0`. Adding one and writing back is the canonical pattern.