使用 Java-8,我可以轻松处理 String
(或任何 CharSequence
)作为 IntStream
使用 chars
或 codePoints
方法。
IntStream chars = "Hello world.".codePoints();
然后我可以操作流的内容
IntStream stars = chars.map(c -> c == ' ' ? ' ': '*');
我一直在寻找一种整洁的方法来打印结果,但我什至找不到简单的方法。我如何放置 int
的这个流s 回到一个可以像我一样打印的表格 String
.
来自以上stars
我希望打印
***** ******
最佳答案
String result = "Hello world."
.codePoints()
//.parallel() // uncomment this line for large strings
.map(c -> c == ' ' ? ' ': '*')
.collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
但是,"Hello world.".replaceAll("[^ ]", "*")
更简单。并非所有东西都能从 lambdas 中受益。
关于java - 将 `IntStream` 打印为 `String` 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266422/