Skip to main content

Word Frequency Counter

Word Frequency Counter in Java


Task


Write a Java program to count the frequency of each word in a given sentence. The program should:


1. Take a sentence as input.

2. Split the sentence into individual words.

3. Count how many times each word appears.

4. Print each word along with its frequency.



Example


Input:


the quick brown fox jumps over the lazy dog


Output:


the : 2

quick : 1

brown : 1

fox : 1

jumps : 1

over : 1

lazy : 1

dog : 1



---


Code


import java.util.HashMap;

import java.util.Map;


public class WordFrequencyCounter {

    public static void main(String[] args) {

        // Input sentence

        String sentence = "the quick brown fox jumps over the lazy dog";


        // Split the sentence into words (using space as delimiter)

        String[] words = sentence.split(" ");


        // Create a HashMap to store words and their counts

        Map<String, Integer> wordCount = new HashMap<>();


        // Loop through each word

        for (String word : words) {

            // If the word already exists in the map, increase its count

            // If not, put it in the map with count 1

            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);

        }


        // Print each word with its frequency

        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {

            System.out.println(entry.getKey() + " : " + entry.getValue());

        }

    }

}



---


Explanation


1. Splitting the sentence


String[] words = sentence.split(" ");


The split(" ") function divides the sentence into words based on spaces.




2. Using HashMap to store counts


Map<String, Integer> wordCount = new HashMap<>();


A HashMap is used because it stores data as key-value pairs.


The key is the word, and the value is the count of how many times the word appears.




3. Counting word frequencies


wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);


getOrDefault(word, 0) → checks if the word already exists in the map.


If yes, it gets its count; if not, it takes 0.


Then we add 1 to update the count.




4. Displaying results


for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {

    System.out.println(entry.getKey() + " : " + entry.getValue());

}


entrySet() gives all key-value pairs from the map.


We print each word (key) and its frequency (value).




✅ This exercise helps you practice String manipulation, HashMap usage, and iteration over a Map in Java.


Comments