Set and Map
At closing time the manager asks two questions: "Which different drinks did we sell today?" and "How many of each?" A list of every sale holds the answer, but digging it out is slow and fiddly. A Set answers the first question by design, and a Map answers the second.
The rule
A Set keeps each value once; a Map finds a value by its key.
A Set is a collection with no duplicates. Adding something already present does nothing, and add returns false to tell you so:
Set<String> soldToday = new HashSet<>();
soldToday.add("Latte");
soldToday.add("Mocha");
soldToday.add("Latte"); // ignored, returns false
System.out.println(soldToday.size()); // 2
System.out.println(soldToday.contains("Mocha")); // truecontains on a HashSet is very fast, however big the set grows, which makes sets ideal for "have we seen this?" checks.
A Map stores key → value pairs. Keys are unique; each one points to exactly one value:
Map<String, Integer> priceCents = new HashMap<>();
priceCents.put("Latte", 300);
priceCents.put("Mocha", 340);
priceCents.put("Latte", 320); // replaces 300
System.out.println(priceCents.get("Latte")); // 320
System.out.println(priceCents.get("Chai")); // null: no such key
System.out.println(priceCents.getOrDefault("Chai", 0)); // 0Counting is a classic Map job. merge adds 1 to the existing count, or starts at 1 if the key is new:
Map<String, Integer> cupsSold = new HashMap<>();
for (String drink : sales) {
cupsSold.merge(drink, 1, Integer::sum);
}Order depends on which implementation you choose:
| Implementation | Iteration order |
|---|---|
HashSet, HashMap |
no promised order |
LinkedHashSet, LinkedHashMap |
the order items were first added |
TreeSet, TreeMap |
sorted by value or key |
To walk through a map, loop over map.entrySet() and use getKey() and getValue() on each entry.
The shortcut
Listen to the question. "Which different…?" or "Have we seen…?" → Set. "How many per…?", "What is the … of…?" → Map, with the thing after "per" or "of" as the key. Then ask whether order matters, and pick Hash, LinkedHash or Tree.
Spot the word
"per drink": the drink name is the key and the count is the value, so a Map.
Drills
Answer fast — trust the rule.
A HashSet<String> receives "Latte", "Tea", "Latte", "Mocha", "Tea". What is its size?
After put("Latte", 300) and then put("Latte", 320), what is get("Latte")?
What does priceCents.get("Chai") return when "Chai" was never added?
A report must list drinks alphabetically with their counts. Which type fits best?
Remember
- A Set keeps each value once; a Map finds a value by its key.
- "Which different" → Set; "how many per" → Map keyed by the thing after "per".
- Traps: expecting HashSet or HashMap to keep order, and
getreturning null for a missing key.
