To reverse a string using Java 8 features, you can use the Stream API in combination with
StringBuilder. Below is an example of how to reverse a string using Java 8.
Java 8 Approach Using Streams:
import java.util.stream.Collectors;
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, Java 8!";
// Reverse the string using Java 8 Stream API
String reversed = input.chars() // Convert the string to an IntStream
.mapToObj(c -> (char) c) // Map the chars to Character
.collect(Collectors.collectingAndThen(
Collectors.toList(),
list -> {
Collections.reverse(list); // Reverse the list
return list.stream(); // Convert the list back to a stream
}))
.map(String::valueOf) // Convert each character back to string
.collect(Collectors.joining()); // Join the characters back into a string
System.out.println("Reversed String: " + reversed);
Explanation:
1. input.chars(): Converts the input string into an IntStream of character values.
2. .mapToObj(c -> (char) c): Converts each character code to a Character object.
3. Collectors.toList(): Collects the characters into a list.
4. Collections.reverse(list): Reverses the list of characters.
5. Collectors.joining(): Joins the characters back into a single string.