Java Programs›Collections›Word Frequency Program

Word Frequency Program in Java

intermediate·  Collections  ·  Map

Problem

A HashMap stores key-value pairs, making it a natural fit for counting how often each item in a collection appears.

Given a sentence, count how many times each word appears.

Input
"the quick fox the lazy fox the dog"
Output
the: 3, quick: 1, lazy: 1 ...

Java Program

Java
import java.util.HashMap; import java.util.Map; public class WordFrequency { public static void main(String[] args) { String text = "the quick fox the lazy fox the dog"; Map<String, Integer> freq = new HashMap<>(); for (String word : text.split(" ")) { // getOrDefault(word, 0) reads the current count, or 0 if unseen, then increments it freq.put(word, freq.getOrDefault(word, 0) + 1); } for (Map.Entry<String, Integer> entry : freq.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }

Output

the: 3 quick: 1 lazy: 1 dog: 1 fox: 2

Core Logic

A HashMap makes this straightforward — split the sentence into words and bump each word's count as you go.

How It Works
  1. 1text.split(" ") breaks the sentence into individual words.
  2. 2A HashMap<String, Integer> tracks each word's running count.
  3. 3freq.getOrDefault(word, 0) reads the current count, or 0 if the word hasn't been seen yet.
  4. 4Adding 1 and calling freq.put(word, ...) stores the updated count in one line.
  5. 5entrySet() is iterated afterward to print every word alongside its final count.
In "the quick fox the lazy fox the dog", "the" ends with a count of 3 and "fox" ends with a count of 2.
💡

Key Point: getOrDefault() removes the need for a separate 'does this key exist yet' check before incrementing.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Every word is visited once to update its count, and the map holds one entry per distinct word, up to n in the worst case.

Key Concepts

HashMapgetOrDefault()entrySet()

Approach 2: Streams + Collectors.groupingBy()

Java
import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; public class WordFrequencyStream { public static void main(String[] args) { String text = "the quick fox the lazy fox the dog"; // Groups equal words together and counts how many are in each group Map<String, Long> freq = Arrays.stream(text.split(" ")) .collect(Collectors.groupingBy(word -> word, Collectors.counting())); freq.forEach((word, count) -> System.out.println(word + ": " + count)); } }

Output

the: 3 quick: 1 lazy: 1 dog: 1 fox: 2

Core Logic

Streams can express the same idea more declaratively — groupingBy plus counting() builds the frequency map in one line.

How It Works
  1. 1Arrays.stream(text.split(" ")) turns the split words into a Stream<String>.
  2. 2Collectors.groupingBy(word -> word, Collectors.counting()) groups equal words together and counts how many are in each group.
  3. 3The result is a Map<String, Long> — note the count is a Long, not an int, since counting() always produces one.
  4. 4freq.forEach((word, count) -> ...) prints every entry using a lambda instead of an explicit entrySet() loop.
Grouping "the quick fox the lazy fox the dog" produces the same counts as the manual version: the: 3, quick: 1, lazy: 1, dog: 1, fox: 2.
💡

Key Point: groupingBy + counting() is the idiomatic modern-Java way to build a frequency map — it reads as 'group by identity, then count', with no manual increment logic at all.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: groupingBy() still visits every word once while building the map, which holds one entry per distinct word just like the manual version.

Key Concepts

StreamCollectors.groupingBy()Collectors.counting()

Interview Questions

How do you ignore punctuation when counting words?

Lower-case the text and split on non-word characters, for example text.toLowerCase().split("\\W+").

How do you find the three most common words?

Sort the map's entries by value in descending order and take the first three, for example with stream().sorted(...).limit(3).

Learn the Concept

Related Programs