Java 8 Program to Reverse Each Word of String

Introduction

Reversing each word in a string is a common text manipulation task. With Java 8, this can be efficiently achieved using streams and lambda expressions. The goal is to take a sentence as input, reverse each word in the sentence, and return the modified sentence with the words reversed but in their original order.

Problem Statement

Create a Java program that:

  • Takes a string input.
  • Reverses each word in the string.
  • Returns and displays the string with each word reversed while maintaining the original word order.

Example 1:

  • Input: "Hello World"
  • Output: "olleH dlroW"

Example 2:

  • Input: "Java 8 Streams"
  • Output: "avaJ 8 smaertS"

Solution Steps

  1. Prompt for Input: Use the Scanner class to read a string input from the user.
  2. Split the String into Words: Use the split() method to divide the string into individual words.
  3. Reverse Each Word Using Streams: Convert the words to a stream, reverse each word, and collect them back into a string.
  4. Display the Result: Print the string with each word reversed.

Java Program

Java 8 Program to Reverse Each Word of a String

import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 Program to Reverse Each Word of a String
 * Author: https://www.javaguides.net/
 */
public class ReverseWords {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        // Step 2: Reverse each word using Java 8 streams
        String result = Stream.of(input.split(" "))          // Split the string into words
                              .map(word -> new StringBuilder(word).reverse().toString())  // Reverse each word
                              .collect(Collectors.joining(" "));  // Join the reversed words back into a string

        // Step 3: Display the result
        System.out.println("Reversed words: " + result);
    }
}

Explanation

  • Input: The program prompts the user to enter a string.

  • Splitting and Reversing Words:

    • The split(" ") method splits the input string into an array of words based on spaces.
    • Stream.of() converts this array into a stream.
    • The map() function applies a transformation to each word in the stream: reversing the word using StringBuilder.
    • The collect(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 but in the original order.

Output Example

Example 1:

Enter a string: Hello World
Reversed words: olleH dlroW

Example 2:

Enter a string: Java 8 Streams
Reversed words: avaJ 8 smaertS

Example 3:

Enter a string: Reverse each word in this sentence
Reversed words: esreveR hcae drow ni siht ecnetnes

Explanation of the Output:

  • The input string is split into words based on spaces.
  • Each word is reversed individually.
  • The reversed words are then combined back into a single string.

Conclusion

This Java 8 program demonstrates how to reverse each word in a string using streams. The map() method with StringBuilder makes the reversal of each word straightforward, and the collect() method allows for reassembling the reversed words into the final output. This approach is efficient and leverages the power of Java 8's functional programming features, making it a modern and elegant solution for string manipulation tasks.

Comments