Skip to content
HashMap
step 1/5

Reading — step 1 of 5

Learn

~2 min readCollections

HashMap

Suppose you need each person's age. With a list you'd store pairs and SCAN the whole thing for every lookup — slow and clumsy. A hash table jumps straight from the key to its entry in (on average) constant time, no matter how large the table grows. Java's implementation is HashMap<K, V> in java.util — plus a keys-only cousin, HashSet, which this lesson's exercise uses.

HashMap — key to value

import java.util.HashMap;

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Alice", 31);                          // same key: OVERWRITES — keys are unique

System.out.println(ages.get("Alice"));          // 31
System.out.println(ages.containsKey("Carol"));  // false
ages.remove("Bob");

Two rules fall out of "keys are unique": put on an existing key replaces its value, and get on a missing key returns null — not an error, not a default. Which sets up a classic crash:

int x = ages.get("Carol");   // NullPointerException!
// get returned null; unboxing null into an int crashes

Defend with getOrDefault:

int x = ages.getOrDefault("Carol", 0);   // 0 — no null in sight

That method also powers the single most useful map idiom — counting occurrences:

HashMap<String, Integer> counts = new HashMap<>();
for (String w : words) {
    counts.put(w, counts.getOrDefault(w, 0) + 1);
}

Iterating

for (var e : ages.entrySet()) {
    System.out.println(e.getKey() + " -> " + e.getValue());
}

HashMap's iteration order is UNSPECIFIED — it can even change as the map grows. Never build output that depends on it. Need insertion order? LinkedHashMap. Sorted keys? TreeMap.

HashSet — just the keys

Often you don't need a value per key — you only need "have I seen this before?" That's HashSet<T>: the same hash machinery, keys only.

import java.util.HashSet;

HashSet<String> seen = new HashSet<>();
seen.add("the");     // true  — newly added
seen.add("quick");   // true
seen.add("the");     // false — already there; the set is unchanged
System.out.println(seen.size());   // 2

Duplicates are ignored automatically — add returns false instead of inserting twice. That makes counting DISTINCT things a three-line job: add everything, then ask for size().

Rule of thumb: data attached to each key → HashMap. Only membership or distinctness → HashSet.

(Both rely on the key type's equals and hashCode. Strings and the numeric wrappers implement them correctly out of the box, which is why they're the usual key types.)

Your exercise

Read one line of space-separated words and print how many DISTINCT words appear. The starter splits the line into String[] words and creates a HashSet<String> seen. Loop, add, print the size:

for (String w : words) {
    seen.add(w);
}
System.out.println(seen.size());

The set silently swallows the repeats — that's the whole trick. The mistake the grader will catch: printing words.length instead of seen.size(). For input the quick brown the there are 4 words but only 3 distinct — the grader expects 3, and the array-length answer 4 fails on the very first test.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…