merge inserts the value when the key is absent and otherwise applies the remapping function, which makes counters a one-liner.
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);
{java=3, kafka=1, sql=1}
after merging sql +10: {java=3, kafka=1, sql=11}
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