Java · Course navigation

Java maps, sets, and duplicate counting

Track counts and distinct values with separate collection roles.

On this page
Before you start

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

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}
2

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1import java.util.Map;
2import java.util.TreeMap;
3import java.util.Set;
4import java.util.TreeSet;
5class 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading