I have one string say "Aniruddh"
and I want to reverse it using lambdas and streams in Java 8. How can I do it?
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);
}
Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
来源:https://stackoverflow.com/questions/47504758/how-can-i-reverse-one-single-string-in-java-8-using-lambda-and-streams