Java 8 – Count the Number of Words in a Given String

Introduction

Counting the number of words in a string is a fundamental task in text processing, commonly used in applications such as text analysis, natural language processing, and user input validation. Whether you’re dealing with sentences, paragraphs, or entire documents, knowing how many words are present is often the first step in text manipulation. Java 8 offers a concise and efficient way to count the number of words in a string using Streams. In this guide, we will explore how to create a Java program that counts the number of words in a given string using Java 8 Streams.

Problem Statement

The task is to create a Java program that:

  • Accepts a string as input.
  • Uses Java 8 Streams to count the number of words in the string.
  • Outputs the total word count.

Example 1:

  • Input: "Hello World"
  • Output: Word Count: 2

Example 2:

  • Input: "Java is a powerful programming language."
  • Output: Word Count: 6

Solution Steps

  1. Input String: Start with a string that can either be hardcoded or provided by the user.
  2. Split the String into Words: Use the split() method to break the string into individual words.
  3. Count the Words: Convert the array of words into a stream and count the number of elements.
  4. Display the Result: Print the total word count.

Java Program

Java 8 Program to Count the Number of Words in a Given String

import java.util.Arrays;

/**
 * Java 8 Program to Count the Number of Words in a Given String
 * Author: https://www.rameshfadatare.com/
 */
public class WordCounter {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "Java is a powerful programming language.";

        // Step 2: Count the number of words using streams
        long wordCount = countWords(input);

        // Step 3: Display the result
        System.out.println("Word Count: " + wordCount);
    }

    // Method to count the number of words in a string
    public static long countWords(String input) {
        return Arrays.stream(input.split("\\s+"))
                .count();
    }
}

Explanation of the Program

  • Input Handling: The program uses the string "Java is a powerful programming language." as an example input. This can be modified to accept input from the user if required.

  • Splitting the String: The split("\\s+") method splits the string into words, where \\s+ is a regular expression that matches any sequence of whitespace characters. This ensures that words are correctly identified even if there are multiple spaces between them.

  • Counting Words: The stream() method converts the array of words into a stream. The count() method then returns the number of elements (words) in the stream.

  • Output: The program prints the total number of words in the input string.

Output Example

Example 1:

Input: Hello World
Output: Word Count: 2

Example 2:

Input: Java is a powerful programming language.
Output: Word Count: 6

Advanced Considerations

  1. Handling Punctuation: The program counts words separated by spaces, so punctuation marks attached to words (e.g., "language.") do not affect the word count. However, if punctuation needs to be excluded, additional preprocessing of the string may be required.

  2. Empty Strings: If the input string is empty or contains only whitespace, the program correctly returns a word count of zero.

  3. Performance Considerations: This approach is efficient for typical string lengths and leverages the functional programming features of Java 8. The use of streams provides a clear and concise method for counting words.

Conclusion

This Java 8 program efficiently counts the number of words in a given string using streams. By leveraging the power of the Stream API, the solution is both concise and powerful, making it suitable for various text processing tasks. Whether you’re analyzing text data, preparing input for further processing, or just working on simple string manipulation tasks, this method provides an effective approach to word counting in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top