Streams: groupingBy with counting builds a frequency map

The classic word count in a single expression. TreeMap::new keeps keys sorted so the output is stable across runs.

Code
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));
Output
java -> 3
kafka -> 1
sql -> 2
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