如何使用 Lambda 和 Streams 在 Java 8 中反转单个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47504758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I reverse one single string in Java 8 using Lambda and Streams?
提问by Aniruddh Dwivedi
I have one string say "Aniruddh"
and I want to reverse it using lambdas and streams in Java 8. How can I do it?
我有一个字符串说"Aniruddh"
,我想在 Java 8 中使用 lambdas 和流来反转它。我该怎么做?
回答by Holger
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.
所以底线是,对于实际应用程序,保持在开头显示的规范解决方案。
回答by vts
Try this for reverse a string using lambda and streams
尝试使用 lambda 和流反转字符串
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(" "));
}
}
回答by Eugene
If you reallywant to do it for learning purposes, why not reverse the char array?
如果你真的为了学习目的而这样做,为什么不反转 char 数组呢?
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();
}
回答by Henrik Aasted S?rensen
The easiest way to achieve what you're asking using streams is probably this:
使用流实现您所要求的最简单方法可能是这样的:
String result = Stream.of("Aniruddh").map(__ -> "hddurinA").findFirst().get();
回答by shinjw
Another approach to reversing your String. You can use an IntStream to pull the correct character out of a char
array.
另一种反转字符串的方法。您可以使用 IntStream 从char
数组中提取正确的字符。
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);
}
回答by Rohan Aggarwal
Function<String, String> reverse = s -> new StringBuilder(s).reverse().toString();
回答by SkyWalker
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.
如果有一种方法可以附加所有字符而不将每个字符转换为String
然后加入它们会更好。这就是为什么我说它看起来效率不高。
回答by Chinmay Bhat
Another alternative way would be to split the string into an array of string and use reduce() on it.
另一种替代方法是将字符串拆分为字符串数组并在其上使用 reduce()。
Stream.of("Aniruddh".split("")).reduce("", (reversed, character) -> character + reversed);
回答by Mehdi najafian
Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots.
给定一个长度为 S 的字符串,反转整个字符串而不反转其中的单个单词。单词用点分隔。
String str="abcd.efg.qwerty";
String reversed = Arrays.asList(str.split("\.")).stream().map(m -> new
StringBuilder(m).reverse().toString()).collect(Collectors.joining("."));
System.out.println(reversed);