Introduction
Reversing a string is a common programming task. Java 8 introduced the Stream API, which makes this task straightforward and efficient. In this guide, we will learn how to reverse a string using Java 8 Streams.
Problem Statement
Write a Java program that:
- Takes a string as input.
- Reverses the string using Java 8 Streams.
- Displays the reversed string.
Example:
- Input:
"Java"
- Output:
"avaJ"
Solution Steps
- Input String: Define the input string that needs to be reversed.
- Convert String to Stream: Convert the string into a stream of characters.
- Reverse the Stream: Reverse the stream of characters.
- Collect Reversed Characters: Collect the reversed characters and form the reversed string.
- Display the Result: Print the reversed string.
Java Program
import java.util.stream.Collectors;
public class ReverseString {
public static void main(String[] args) {
// Step 1: Define the input string
String input = "Java";
// Step 2: Reverse the string using Streams
String reversed = input.chars() // Convert the string to an IntStream of character codes
.mapToObj(c -> (char) c) // Convert IntStream to Stream<Character>
.collect(Collectors.collectingAndThen( // Collect the characters
Collectors.toList(), // Collect them into a List
list -> { // Then reverse the list
java.util.Collections.reverse(list);
return list.stream();
}
)) // Join the reversed list into a new string
.map(String::valueOf)
.collect(Collectors.joining());
// Step 3: Display the result
System.out.println("Reversed String: " + reversed);
}
}
Output
Reversed String: avaJ
Explanation
Step 1: Define the Input String
We start by defining the string:
String input = "Java";
This is the string we want to reverse.
Step 2: Reverse the String Using Streams
To reverse the string:
- Convert the String to a Stream of Characters:
input.chars()
converts the string into a stream of character codes (as anIntStream
), andmapToObj(c -> (char) c)
converts those character codes into a stream ofCharacter
objects. - Collect into a List: The stream of characters is collected into a list using
Collectors.toList()
. - Reverse the List: We reverse the list using
java.util.Collections.reverse()
. - Join the Characters Back into a String: The reversed characters are streamed back and joined into a string using
Collectors.joining()
.
Step 3: Display the Result
The reversed string is printed using:
System.out.println("Reversed String: " + reversed);
Output Example
Example 1:
For the input "Java"
, the output is:
Reversed String: avaJ
Example 2:
For the input "Hello"
, the output is:
Reversed String: olleH
Conclusion
This program demonstrates how to reverse a string using Java 8 Streams. By converting the string into a stream of characters, reversing the stream, and then joining the characters back together, we efficiently reverse the string. This approach leverages modern Java features to solve a classic programming problem.
Comments
Post a Comment
Leave Comment