Convert IntStream to String in Java and Vice Versa

Since Java doesn’t offer any character Stream, we can create an IntStream (stream of ints) of characters when dealing with strings. In this post, we will discuss how to convert String to IntStream and IntStream to String in Java.


 

1. Convert String to IntStream

Simplest solution to get an IntStream from a String is to call codePoints() or chars() method on the String as shown below:

 

Download   Run Code

Output:

84
101
99
104
105
101
32
68
101
108
105
103
104
116

 

2. Convert IntStream to String

Converting IntStream to String is not so straightforward in Java. The idea is to use a Collector which accumulates the values using a StringBuilder.

 

Download   Run Code

Output:

Techie Delight

 

3. Convert Character Array to IntStream

If we have a character array, we can convert it into Stream of Characters and then use flatMapToInt to convert the Stream into an IntStream.

 

Download   Run Code

Output:

84
101
99
104
105
101

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz