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

六月ゝ 毕业季﹏ 提交于 2019-12-04 06:36:01

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.

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(" "));
        }
    }

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();
}

The easiest way to achieve what you're asking using streams is probably this:

String result = Stream.of("Aniruddh").map(__ -> "hddurinA").findFirst().get();

Another approach to reversing your String. You can use an IntStream to pull the correct character out of a char array.

public static void main(String[] args) {
    char[] charArray = "Aniruddh".toCharArray();
    IntStream.range(0, charArray.length)
        .mapToObj(i -> charArray[(charArray.length - 1) - i])
        .forEach(System.out::print);
}
Rohan Aggarwal
Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!