Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a string from an IntStream of code point numbers?

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?

like image 946
Basil Bourque Avatar asked Aug 01 '19 23:08

Basil Bourque


2 Answers

not to forget the Java IO library:
use IntStream::collect with a StringWriter

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.
        StringWriter::new,         // Supplier<R> supplier
        StringWriter::write,       // ObjIntConsumer<R> accumulator
        (w1, w2) -> w1.write(      // BiConsumer<R,R> combiner
            w2.toString() ) )
    .toString();
like image 169
Kaplan Avatar answered Nov 08 '22 01:11

Kaplan


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 );
like image 11
shmosel Avatar answered Nov 08 '22 02:11

shmosel