Introduction
Reversing each word in a string is a common task in text manipulation, often used in scenarios like cryptography, data transformation, and formatting text for specific requirements. While reversing an entire string is straightforward, reversing each word individually while maintaining the order of the words adds a layer of complexity. Java 8 provides a powerful and elegant way to accomplish this using Streams. In this guide, we will explore how to create a Java program that reverses each word of 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 reverse each word in the string while preserving the order of the words.
- Outputs the string with each word reversed.
Example 1:
- Input: "Hello World"
- Output: "olleH dlroW"
Example 2:
- Input: "Java Programming Language"
- Output: "avaJ gnimmargorP egaugnaL"
Solution Steps
- Input String: Start with a string that can either be hardcoded or provided by the user.
- Split the String into Words: Use the split()method to break the string into individual words.
- Reverse Each Word: Convert the array of words into a stream, reverse each word using StringBuilder, and then collect the results.
- Combine and Display the Result: Join the reversed words back into a single string and print the result.
Java Program
Java 8: Reverse Each Word of a String
import java.util.Arrays;
import java.util.stream.Collectors;
/**
 * Java 8: Reverse Each Word of a String
 * Author: https://www.rameshfadatare.com/
 */
public class ReverseEachWord {
    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "Hello World";
        // Step 2: Reverse each word using streams
        String result = reverseEachWord(input);
        // Step 3: Display the result
        System.out.println(result);
    }
    // Method to reverse each word in a string
    public static String reverseEachWord(String input) {
        return Arrays.stream(input.split("\\s+"))
                .map(word -> new StringBuilder(word).reverse().toString())
                .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.
- 
Reversing Each Word: The map()method processes each word in the stream. TheStringBuilder(word).reverse().toString()constructs a newStringBuilderfor each word, reverses it, and converts it back to a string.
- 
Joining the Words: The Collectors.joining(" ")method joins the reversed words back into a single string, with each word separated by a space.
- 
Output: The program prints the string with each word reversed. 
Output Example
Example 1:
Input: Hello World
Output: olleH dlroW
Example 2:
Input: Java Programming Language
Output: avaJ gnimmargorP egaugnaL
Advanced Considerations
- 
Handling Punctuation: The program reverses words as they are, including any punctuation attached to them. If you need to handle punctuation separately, additional preprocessing may be required. 
- 
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 reversing each word in a string. 
- 
Empty Strings: The program handles empty strings gracefully by returning an empty string without errors. 
Conclusion
This Java 8 program efficiently reverses each word in a string using streams. By leveraging the power of the Stream API, the solution is both concise and powerful, making it suitable for various text manipulation tasks. Whether you’re formatting text, working on data transformation, or implementing specific cryptographic techniques, this method provides an effective approach to reversing words in a string in Java.