Java maps, sets, and duplicate counting
Track counts and distinct values with separate collection roles.
On this page
Generics, loops, and strings.
- Track counts and distinct values with separate collection roles.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A Map associates keys with values; a Set records distinct values. getOrDefault avoids a missing-key null result while counting.
TreeMap provides sorted key order, and TreeSet provides sorted unique values. Using these ordered collections makes the displayed result deterministic.
Code example
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
Map<String, Integer> counts = new TreeMap<>();
Set<String> unique = new TreeSet<>();
for (String word : new String[]{"red", "blue", "red"}) {
counts.put(word, counts.getOrDefault(word, 0) + 1);
unique.add(word);
}
System.out.println(counts);
System.out.println(unique.size());
}
}{blue=1, red=2}
2Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
import java.util.Map;import java.util.TreeMap;import java.util.Set;import java.util.TreeSet;class Main { public static void main(String[] args) { Map<String, Integer> counts = new TreeMap<>(); Set<String> unique = new TreeSet<>(); for (String word : new String[]{"red", "blue", "red"}) { counts.put(word, counts.getOrDefault(word, 0) + 1); unique.add(word); } System.out.println(counts); System.out.println(unique.size()); }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create an ordered map. | counts = {} | — | |
| Process red, blue, and red, incrementing existing counts. | counts = {blue=1, red=2} | — | |
| The repeated red does not create a third distinct entry. | unique = [blue, red] | — | |
| Print in sorted key order. | unique = [blue, red] | {blue=1, red=2} | |
| Print the distinct count. | unique = [blue, red] | {blue=1, red=2}
2 |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(n log k) comparisons for n words and k distinct keys, ignoring variable string comparison cost; O(k) storage.
- HashMap does not promise the same iteration order.
- An object's ordering/equality rules must be suitable for its use as a key.
Try it yourself
Add another blue token.
Reveal answer and reasoning
The map becomes {blue=2, red=2}; the distinct count remains 2.