Java Program to Count Occurrences of Words in a String

In this post, we'll introduce beginners to a simple Java program that counts the occurrences of each word in a given string.

Basic Concept: 

We will break the string into individual words and then count the occurrences of each word using a data structure called HashMap.

Java Program to Count Occurrences of Words in a String

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordCounter {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your string:");
        String input = scanner.nextLine();

        Map<String, Integer> wordCounts = countWords(input);

        System.out.println("Occurrences of each word:");
        for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

    public static Map<String, Integer> countWords(String input) {
        Map<String, Integer> wordCountMap = new HashMap<>();

        String[] words = input.split("\\s+");

        for (String word : words) {
            word = word.toLowerCase();
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
        }

        return wordCountMap;
    }
}

Output:

Enter your string:
Hello world! Hello everyone!
Occurrences of each word:
hello: 2
world!: 1
everyone!: 1

Step by Step Explanation: 

User Input: 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your string:");
        String input = scanner.nextLine();
We start by fetching a string input from the user using the Scanner class

Breaking the String into Words:
 String[] words = input.split("\\s+");
Using the split method, we break the input string wherever whitespace (\\s+) is found, resulting in an array of words. 

Using a HashMap: 
Map<String, Integer> wordCountMap = new HashMap<>();
HashMap is used to store each word as the key and its frequency as the value. This data structure allows for efficient look-ups and insertions. 

Counting the Words: 
        for (String word : words) {
            word = word.toLowerCase();
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
        }
We iterate through the words and, for each word, increment its count in our HashMap. The getOrDefault method ensures that if a word is not already present in the map, it uses a default value of 0. 

Displaying Results: 
        for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
Finally, we go through the entries of our HashMap and print each word with its corresponding count.

Conclusion

Counting the occurrences of words in a string serves as an excellent introduction to text manipulation and the usage of advanced data structures like HashMap in Java. While the current program provides a foundational understanding, there's a lot more to explore, including handling punctuations, special characters, and more. As you continue your Java learning journey, remember that these foundational exercises serve as building blocks for more complex applications. Keep coding and exploring!

Related Java String Programs with Output

Comments