Java maps, sets, and duplicate counting

A Map associates keys with values; a Set records distinct values. getOrDefault avoids a missing-key null result while counting.

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());
    }
}
Read the full lesson