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

梦想与她 提交于 2019-12-06 02:34:12

问题


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


回答1:


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.




回答2:


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



回答3:


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



回答4:


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

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



回答5:


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



回答6:


Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();



回答7:


Here is another way, doesn't seem super efficient but will explain why:

String s = "blast";
IntStream.range(0, s.length()).           // create index [0 .. s.length - 1] 
   boxed().                               // the next step requires them boxed
   sorted(Collections.reverseOrder()).    // indices in reverse order
   map(i -> String.valueOf(s.charAt(i))). // grab each index's character 
   collect(Collectors.joining());         // join each single-character String into the final String

It would be better if there was a way to append all the Characters without converting each to String and then joining them. That's why I said it doesn't seem super efficient.



来源:https://stackoverflow.com/questions/47504758/how-can-i-reverse-one-single-string-in-java-8-using-lambda-and-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!