Maps: merge is the cleanest way to count

merge inserts the value when the key is absent and otherwise applies the remapping function, which makes counters a one-liner.

Code
Map<String, Integer> counts = new TreeMap<>();
for (String word : List.of("java", "sql", "java", "kafka", "java")) {
    counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);

counts.merge("sql", 10, Integer::sum);
System.out.println("after merging sql +10: " + counts);
Output
{java=3, kafka=1, sql=1}
after merging sql +10: {java=3, kafka=1, sql=11}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30