Java, lesson 13
You met HashMap in the collections lesson. Maps and sets are behind a huge number of everyday
tasks: counting words, grouping orders by customer, removing duplicates, comparing two lists. This
lesson shows the idiomatic tools for each.
The classic counting pattern looks up the old count, adds one and stores it back. merge does
all of that in one call:
Read merge(key, 1, Integer::sum) as: "if the key is new, store 1; otherwise combine the old
value and 1 with Integer::sum". The older spelling,
counts.put(k, counts.getOrDefault(k, 0) + 1), does the same thing.
2 exercises to try what you just read.
To group items into lists, you need "the list for this key, created if missing".
computeIfAbsent returns the existing value or creates one with the function you give it:
| Map | Iteration order | Use it when |
|---|---|---|
HashMap | no particular order | you only look things up (fastest) |
LinkedHashMap | order of insertion | you want to keep the input order |
TreeMap | sorted by key | you want sorted output, or ranges |
A TreeMap also answers questions such as firstKey(), lastKey() and floorKey(x) (the
largest key not above x), which are handy for things like price bands.
To sort a map by its values (say, most frequent word first), copy the entries to a list and sort it:
A Set holds each value at most once, and contains is fast. Adding a duplicate does nothing
(add returns false). The same three flavours exist: HashSet (no order), LinkedHashSet
(insertion order) and TreeSet (sorted).
The bulk methods modify the set they are called on, so start from a copy:
a.containsAll(b) tells you whether b is a subset of a.
Sets and map keys rely on equals and hashCode. Strings, numbers and records implement both
correctly, which is one more reason records make great keys.
Read all of the input. Split it into words: a word is a run of letters (a–z, A–Z); every
other character separates words. Ignore case by turning words into lower case. Print the three
most frequent words as <word> <count>, most frequent first; break ties alphabetically. If there
are fewer than three distinct words, print them all. If there are no words, print No words.
Hint: line.toLowerCase().split("[^a-z]+") can produce an empty first element; skip empty
strings.
Sample input:
Sample output:
The first line lists the members of the chess club, the second line the members of the drama club (names separated by spaces; a line may be empty, and a name may be repeated by mistake). Using sets, print four lines:
Both: followed by the names in both clubs,Chess only: names only in chess,Drama only: names only in drama,Total: the number of different people in at least one club.List names in alphabetical order separated by , . If a list is empty, print - instead.
Sample input:
Sample output:
Map<String, Integer> counts = new HashMap<>();
for (String fruit : List.of("apple", "pear", "apple")) {
counts.merge(fruit, 1, Integer::sum);
}
// {apple=2, pear=1}Map<Character, List<String>> byLetter = new TreeMap<>();
for (String name : List.of("ana", "bo", "al", "bea")) {
byLetter.computeIfAbsent(name.charAt(0), k -> new ArrayList<>()).add(name);
}
// {a=[ana, al], b=[bo, bea]}List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()));Set<String> seen = new HashSet<>();
for (String word : words) {
if (!seen.add(word)) {
System.out.println("Repeated: " + word);
}
}Set<String> a = new TreeSet<>(List.of("ana", "bo", "cy"));
Set<String> b = new TreeSet<>(List.of("bo", "cy", "dan"));
Set<String> union = new TreeSet<>(a);
union.addAll(b); // [ana, bo, cy, dan]
Set<String> both = new TreeSet<>(a);
both.retainAll(b); // [bo, cy] intersection
Set<String> onlyA = new TreeSet<>(a);
onlyA.removeAll(b); // [ana] differenceThe cat and the hat.
The CAT sat!the 3
cat 2
and 1ana bo cy ana
cy dan boBoth: bo, cy
Chess only: ana
Drama only: dan
Total: 4