从代码点编号的IntStream生成字符串? [英] Make a string from an IntStream of code point numbers?
问题描述
如果我正在使用Java流,并以 CharSequence
例如 String
?
If I am working with Java streams, and end up with an IntStream
of code point numbers for Unicode characters, how can I render a CharSequence
such as a String
?
String output = "input_goes_here".codePoints(). ??? ;
我找到了 codePoints()
方法在几个接口上所有都生成 IntStream
代码点的类。但是我还找不到能够接受相同内容的构造函数或工厂方法。
I have found a codePoints()
method on several interfaces & classes that all generate an IntStream
of code points. Yet I have not been able to find any constructor or factory method that accepts the same.
-
CharSequence :: codePoints ()→IntStream
-
String :: codePoints()→IntStream
-
StringBuilder :: codePoints()→IntStream
CharSequence::codePoints() → IntStream
String::codePoints() → IntStream
StringBuilder::codePoints() → IntStream
我正在寻找相反的情况:
I am looking for the converse:
➥如何实例化 String
或 CharSequence
等来自代码点的 IntStream
吗?
➥ How to instantiate a String
or CharSequence
or such from an IntStream
of code points?
推荐答案
使用 IntStream :: collect
和 StringBuilder
。
Use IntStream::collect
with a StringBuilder
.
String output =
"input_goes_here"
.codePoints() // Generates an `IntStream` of Unicode code points, one `Integer` for each character in the string.
.collect( // Collect the results of processing each code point.
StringBuilder::new, // Supplier<R> supplier
StringBuilder::appendCodePoint, // ObjIntConsumer<R> accumulator
StringBuilder::append // BiConsumer<R,R> combiner
)
.toString()
;
如果您更喜欢 CharSequence
接口在具体的 String
,只需将 toString()
放在最后即可。返回的 StringBuilder
是 CharSequence
。
If you prefer the more general CharSequence
interface over concrete String
, simply drop the toString()
at the end. The returned StringBuilder
is a CharSequence
.
IntStream codePointStream = "input_goes_here".codePoints ();
CharSequence output = codePointStream.collect ( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append );
这篇关于从代码点编号的IntStream生成字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!