Basil Bourque :
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(). ??? ;
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
I am looking for the converse:
➥ How to instantiate a String
or CharSequence
or such from an IntStream
of code points?
shmosel :
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()
;
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 );