Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse one single string in Java 8 using Lambda and Streams?

I have one string say "Aniruddh" and I want to reverse it using lambdas and streams in Java 8. How can I do it?

like image 700
Aniruddh Dwivedi Avatar asked Nov 27 '17 05:11

Aniruddh Dwivedi


People also ask

How do you reverse a string using lambda expression?

We can reverse a string entered by the user using the charAt() method of String class to extract characters from the string and append them in reverse order to reverse the entered string.

How do you reverse a string in Java 8?

String reversed = str. chars() . mapToObj(c -> (char)c) . reduce("", (s,c) -> c+s, (s1,s2) -> s2+s1);

How can we reverse a single string using lambdas and streams?

In Java 8, how can we reverse a single string using lambdas and streams? Reversing string in Java can be done in different ways. Even in Java 8 you can use StringBuffer () class and reverse String. However we can also use lamda expressions to do so:- Example below I am taking String array and each String in array is reversed.

How to reverse string in Java 8 streams?

Following is another approach to reverse the input String str using Java 8 streams API. String abc = Arrays.asList (str).stream () .map (s -> new StringBuilder (s).reverse ().toString ()) .collect (Collectors.toList ()).get (0);

How to reverse string class in Java?

String class in Java does not have reverse () method, however StringBuilder class has built in reverse () method. 3. StringBuilder class do not have toCharArray () method, while String class does have toCharArray () method. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

How to reverse a list of characters in Java?

Java also has built in reverse () method for the Collections class. Since Collections class reverse () method takes a list object , to reverse the list , we will pass the ArrayList object which is a type of list of characters. 1. We copy String contents to an object of ArrayList.


3 Answers

Given a string like

String str = "Aniruddh";

the canonical solution is

String reversed = new StringBuilder(str).reverse().toString();

If, perhaps for educational purposes, you want to solve this by streaming over the string’s characters, you can do it like

String reversed = str.chars()
    .mapToObj(c -> (char)c)
    .reduce("", (s,c) -> c+s, (s1,s2) -> s2+s1);

This is not only much more complicated, it also has lots of performance drawbacks.

The following solution eliminates boxing related overhead

String reversed = str.chars()
    .collect(StringBuilder::new, (b,c) -> b.insert(0,(char)c), (b1,b2) -> b1.insert(0, b2))
    .toString();

but is still less efficient as inserting into the beginning of an array based buffer implies copying all previously collected data.

So the bottom line is, for real applications, stay with the canonical solution shown at the beginning.

like image 199
Holger Avatar answered Oct 25 '22 04:10

Holger


Try this for reverse a string using lambda and streams

import java.util.stream.Stream;
import java.util.stream.Collectors;

    public class Test  {


        public static void main(String[] args) {

            System.out.println(reverse("Anirudh"));;
        }
        public static String reverse(String string) {
            return Stream.of(string)
                .map(word->new StringBuilder(word).reverse())
                .collect(Collectors.joining(" "));
        }
    }
like image 39
Vishnu T S Avatar answered Oct 25 '22 03:10

Vishnu T S


If you really want to do it for learning purposes, why not reverse the char array?

public static String reverse(String test) {
    return IntStream.range(0, test.length())
            .map(i -> test.charAt(test.length() - i - 1))
            .collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append)
            .toString();
}
like image 4
Eugene Avatar answered Oct 25 '22 03:10

Eugene