Java 8 Program to Reverse Each Word of String

1. Introduction

Reversing each word in a string is a common text manipulation task that can be approached in various ways. With Java 8, the introduction of the Stream API added powerful new capabilities for processing collections of objects, including strings. In this blog post, we'll demonstrate how to reverse each word in a given string using Java 8 Streams, showcasing a functional approach to solving this problem.

2. Program Steps

1. Define the input string.

2. Split the string into words using a space as a delimiter.

3. Use Java 8 Streams to process each word.

4. Reverse each word and collect the results.

5. Join the reversed words back into a single string.

6. Display the resulting string.

3. Code Program

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

public class ReverseEachWord {
    public static void main(String[] args) {
        // Input string
        String input = "Java 8 is great";

        // Splitting the input string into words and processing each word with a stream
        String result = Arrays.stream(input.split(" "))
                              .map(word -> new StringBuilder(word).reverse().toString()) // Reversing each word
                              .collect(Collectors.joining(" ")); // Joining the reversed words back into a string

        // Displaying the result
        System.out.println("Original string: " + input);
        System.out.println("Reversed words: " + result);
    }
}

Output:

Original string: Java 8 is great
Reversed words: avaJ 8 si taerg

Explanation:

1. The program starts by defining an input string that contains multiple words.

2. The split() method is used to divide the input string into an array of words, splitting at each space.

3. The Arrays.stream() method converts the array of words into a Stream, allowing each word to be processed individually.

4. The map() intermediate operation is applied to each word in the stream. Inside the map() method, a new StringBuilder is instantiated with the word, and the reverse() method is called to reverse the word. The toString() method then converts the StringBuilder back into a string.

5. After all words have been reversed, the collect() terminal operation is used with Collectors.joining(" ") to merge the reversed words back into a single string, using a space as a delimiter between words.

6. Finally, the original string and the string with reversed words are printed to the console, demonstrating the transformation.

7. This example illustrates the power of Java 8 Streams for processing collections of data in a concise and expressive manner.

Comments