Java: Count word frequencies with groupingBy + counting

Combine groupingBy with the counting downstream collector for a frequency map.

Code
String text = "a b a c b a";
Map<String, Long> freq = Arrays.stream(text.split(" "))
        .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(freq);
Output
{a=3, b=2, c=1}
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-26