Java 8 – Capitalize the First Letter of Each Word in a String

Introduction

Capitalizing the first letter of each word in a string is a common requirement in text formatting and user interface design. This task is particularly useful when displaying titles, headings, or user input in a more readable format. With Java 8, you can achieve this efficiently using Streams. In this guide, we will demonstrate how to create a Java program that capitalizes the first letter of each word in a 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 capitalize the first letter of each word in the string.
  • Outputs the newly formatted string.

Example 1:

  • Input: "hello world"
  • Output: "Hello World"

Example 2:

  • Input: "java programming language"
  • Output: "Java Programming Language"

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. Capitalize Each Word: Convert the array of words into a stream, capitalize the first letter of each word, and then collect the results.
  4. Combine and Display the Result: Join the capitalized words back into a single string and print the result.

Java Program

Java 8 Program to Capitalize the First Letter of Each Word in a String

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * Java 8 Program to Capitalize the First Letter of Each Word in a String
 * Author: https://www.rameshfadatare.com/
 */
public class CapitalizeFirstLetter {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "hello world";

        // Step 2: Capitalize the first letter of each word using streams
        String result = capitalizeWords(input);

        // Step 3: Display the result
        System.out.println(result);
    }

    // Method to capitalize the first letter of each word in a string
    public static String capitalizeWords(String input) {
        return Arrays.stream(input.split("\\s+"))
                .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
                .collect(Collectors.joining(" "));
    }
}

Explanation of the Program

  • Input Handling: The program uses the string "hello world" 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.

  • Capitalizing Each Word: The map() method processes each word in the stream. The first character of each word is capitalized using substring(0, 1).toUpperCase(), and the rest of the word is converted to lowercase with substring(1).toLowerCase() to ensure consistent capitalization.

  • Joining the Words: The Collectors.joining(" ") method joins the capitalized words back into a single string, with each word separated by a space.

  • Output: The program prints the newly formatted string where the first letter of each word is capitalized.

Output Example

Example 1:

Input: hello world
Output: Hello World

Example 2:

Input: java programming language
Output: Java Programming Language

Advanced Considerations

  1. Handling Punctuation: If the input string contains punctuation attached to words (e.g., "hello, world"), you may need to further refine the split() logic or preprocess the string to ensure proper capitalization.

  2. Mixed Case Input: The program converts the rest of each word to lowercase after capitalizing the first letter. This ensures consistent formatting even if the input string is in mixed case.

  3. Handling Empty Strings: If the input string is empty, the program will return an empty string without any errors.

Conclusion

This Java 8 program efficiently capitalizes the first letter of each word in a string using streams. By leveraging the power of the Stream API, the solution is concise, readable, and effective for various text formatting tasks. Whether you’re preparing strings for display in a user interface, processing user input, or working on data cleaning, this method provides a reliable approach to capitalizing words in Java.

Leave a Comment

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

Scroll to Top