Java 8 Program To Reverse a String

Java Program to Reverse a String using StringBuilder.reverse() Method

Reversing a string is a fundamental operation in programming, often encountered in introductory computer science courses and technical interviews. It involves rearranging the characters of the string so that the original string is mirrored. This blog post will demonstrate a method to reverse a string using StringBuilder.reverse() method and Java 8 Stream API.

Program Steps

1. Convert the string into a stream of characters.

2. Reverse the stream of characters.

3. Collect the reversed stream back into a string.

4. Display the reversed string.

Code Program

import java.util.stream.Collectors;

public class ReverseString {
    public static void main(String[] args) {
        String originalString = "hello"; // The original string to be reversed

        // Step 1 and 2: Converting to stream and reversing
        String reversedString = new StringBuilder(originalString).reverse().toString();

        // Step 3: The stream is implicitly collected back into a string by StringBuilder

        // Step 4: Displaying the reversed string
        System.out.println("Original string: " + originalString);
        System.out.println("Reversed string: " + reversedString);
    }
}

Output:

Original string: hello
Reversed string: olleh

Explanation:

1. The program starts with a string originalString set to "hello". The task is to reverse this string, producing "olleh".

2. Instead of directly using the Stream API, the program leverages the StringBuilder class, which is efficient for string manipulation. The StringBuilder is initialized with originalString, and its reverse() method is called to reverse the string. This approach is preferred for its simplicity and performance compared to manually reversing a stream of characters.

3. The reverse() method modifies the StringBuilder instance in place. To obtain the reversed string, toString() is called on the StringBuilder.

4. Finally, both the original and reversed strings are printed to the console, verifying that the string has been correctly reversed. This example illustrates a practical application of Java's built-in methods for string manipulation, achieving the goal with minimal code and without explicitly using streams. It demonstrates how Java 8 and its later versions enhance the expressiveness and efficiency of common programming tasks.

Java Program to Reverse a String using Java 8 Stream API

Reversing a string using Java 8's Stream API illustrates the power and flexibility of functional programming in Java. The Stream API, introduced in Java 8, provides a declarative approach to processing sequences of elements, including strings. 

Let's demonstrate how to reverse a string by converting it to a stream of characters, processing it with the Stream API, and then collecting the results into a string.

Program Steps

1. Convert the string to a stream of characters.

2. Convert the character stream into an array or a list.

3. Reverse the array or list.

4. Convert the reversed array or list back into a stream.

5. Collect the stream back into a string.

6. Display the reversed string.

Code Program

import java.util.Collections;
import java.util.stream.Collectors;

public class ReverseStringUsingStream {
    public static void main(String[] args) {
        String originalString = "Hello World"; // Step 1: Original string

        String reversedString = originalString
            // Step 1 & 2: Convert the string to a stream of characters and collect into a list
            .chars()
            .mapToObj(c -> (char)c)
            .collect(Collectors.toList())
            // Step 3: Reverse the list
            .stream()
            .sorted(Collections.reverseOrder())
            // Step 4 & 5: Convert the reversed list back into a stream, then collect into a string
            .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
                Collections.reverse(list);
                return list.stream();
            }))
            .map(String::valueOf)
            .collect(Collectors.joining());

        // Step 6: Display the reversed string
        System.out.println("Original string: " + originalString);
        System.out.println("Reversed string: " + reversedString);
    }
}

Output:

Original string: Hello World
Reversed string: dlroW olleH

Explanation:

1. The program begins with an originalString set to "Hello World". The objective is to reverse this string using the Stream API.

2. The string is first converted into a stream of characters using .chars(), then each int is mapped to its corresponding char, and collected into a list.

3. This approach initially attempted to reverse the stream directly, but streams don't support direct reversal. Instead, the list is collected, and then a manual reverse operation is performed on the list.

4. The reversed list is converted back into a stream. Each character is then mapped to a string and collected into a single string using Collectors.joining().

5. Finally, the program prints both the original and the reversed strings. The output confirms the string has been successfully reversed using Java 8's Stream API, highlighting a functional approach to solving common programming tasks.

Comments