Java 8 Streams: IntStream to String(Java 8 流:IntStream 到字符串)
问题描述
在 Java 8 流 API 中,对任何 String
对象调用 chars()
会返回一个包含所有字符的 IntStream
对象.
In Java 8 streams API, calling chars()
on any String
object returns an IntStream
object containing all the characters.
将返回的 IntStream
对象转换回 String
的正确方法是什么?调用 toArray()
会给我一个 int[]
,它不被任何 String
构造函数接受.
What would be the correct way to convert the returned IntStream
object back to a String
? Calling toArray()
would give me an int[]
, which is not accepted by any of the String
constructor.
推荐答案
你可以使用toArray()
,然后String(int[], int, int)
构造函数.这并不完全令人满意,因为 chars()
被指定返回 UTF-16 代码单元,基本上:
You can use toArray()
, then the String(int[], int, int)
constructor. This isn't entirely satisfactory as chars()
is specified to return UTF-16 code units, basically:
返回一个 int 流,对该序列中的 char 值进行零扩展.任何映射到代理代码点的字符都会未经解释地传递.
Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted.
使用 codePoints()
相反会更符合这个构造函数,它需要代码点而不是 UTF-16 代码单元.否则(使用 chars
)如果您的原始字符串 确实 包含代理对,您可能会发现错误 - 我没有尝试过,但它会有意义.
Using codePoints()
instead would be more in-keeping with this constructor, which expects code points rather than UTF-16 code units. Otherwise (with chars
) if your original string does contain surrogate pairs, you may find you get an error - I haven't tried it, but it would make sense.
我不知道不先转换为数组的简单方法.
I don't know of a simple way of doing this without converting to an array first.
这篇关于Java 8 流:IntStream 到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 流:IntStream 到字符串


基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01