Java 8 Streams:IntStream到String [英] Java 8 Streams: IntStream to String
问题描述
在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 $的正确方法是什么? c $ c>对象回到
构造函数。字符串
?调用 toArray()
会给我一个 int []
,任何<$ c $都不接受c>字符串
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值进行零扩展。任何映射到代理代码点的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 Streams:IntStream到String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!