如何使用Lambda和Streams在Java 8中反转单个字符串? [英] How can I reverse one single string in Java 8 using Lambda and Streams?

查看:688
本文介绍了如何使用Lambda和Streams在Java 8中反转单个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串说Aniruddh我想在Java 8中使用lambdas和stream来反转它。我该怎么做?

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

推荐答案

给定一个字符串

String str = "Aniruddh";

规范解决方案是

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.

这篇关于如何使用Lambda和Streams在Java 8中反转单个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆