The classic word count in a single expression. TreeMap::new keeps keys sorted so the output is stable across runs.
var words = List.of("java", "sql", "java", "kafka", "sql", "java");
Map<String, Long> freq = words.stream()
.collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting()));
freq.forEach((word, count) -> System.out.println(word + " -> " + count));
java -> 3
kafka -> 1
sql -> 2
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