0% found this document useful (0 votes)
32 views2 pages

Explanation: Input - Chars .Maptoobj (C - (Char) C) Collectors - Tolist

Java 8 Programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views2 pages

Explanation: Input - Chars .Maptoobj (C - (Char) C) Collectors - Tolist

Java 8 Programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

You might also like