Java maps, sets, and duplicate counting
Track counts and distinct values with separate collection roles.
Java
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());
}
}Output
{blue=1, red=2}
2Explanation
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.
Explore the dry run
Guided walkthroughReady
1
import java.util.Map;2
import java.util.TreeMap;3
import java.util.Set;4
import java.util.TreeSet;5
class Main {6
public static void main(String[] args) {7
Map<String, Integer> counts = new TreeMap<>();8
Set<String> unique = new TreeSet<>();9
for (String word : new String[]{"red", "blue", "red"}) {10
counts.put(word, counts.getOrDefault(word, 0) + 1);11
unique.add(word);12
}13
System.out.println(counts);14
System.out.println(unique.size());15
}16
}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 |
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.