Simplest way to print an `IntStream` as a `String`(将“IntStream打印为“String的最简单方法)
问题描述
使用 Java-8,我可以使用 chars<轻松地将 String(或任何 CharSequence)视为 IntStream/code> 或 codePoints 方法.
With Java-8 I can easily treat a String (or any CharSequence) as an IntStream using either the chars or the codePoints method.
IntStream chars = "Hello world.".codePoints();
然后我可以操作流的内容
I can then manipulate the contents of the stream
IntStream stars = chars.map(c -> c == ' ' ? ' ': '*');
我一直在寻找一种整洁的方法来打印结果,但我什至找不到简单的方法.如何将这个 int 流放回可以打印的表单,就像我可以打印 String 一样.
I have been hunting for a tidy way to print the results and I cant even find a simple way. How do I put this stream of ints back into a form that can be printed like I can a String.
从上面的stars希望能打印出来
From the above stars I hope to print
***** ******
推荐答案
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 中受益.
But still, "Hello world.".replaceAll("[^ ]", "*") is simpler. Not everything benefits from lambdas.
这篇关于将“IntStream"打印为“String"的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将“IntStream"打印为“String"的最简单方法
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
