Convert IntStream to String in Java and vice versa
Since Java doesn’t offer any character stream, we can create an IntStream (a stream of ints) of characters when dealing with strings. This post will discuss how to convert string to IntStream and IntStream to string in Java.
1. Convert String to IntStream
The simplest solution to get an IntStream from a string is to call the codePoints() or chars() method on the string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.stream.IntStream; class Main { public static void main(String[] args) { String input = "Techie Delight"; // Convert `String` to `IntStream` IntStream intStream = input.codePoints(); intStream.forEach(System.out::println); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.stream.IntStream; class Main { public static void main(String[] args) { String input = "Techie Delight"; // Convert `IntStream` to `String` String string = input.codePoints() // IntStream .collect(StringBuilder::new, // supplier StringBuilder::appendCodePoint, // accumulator StringBuilder::append) // combiner .toString(); System.out.println(string); } } |
Output:
Techie Delight
3. Convert Character array to IntStream
If we have a character array, we can convert it into a stream of Characters and then use flatMapToInt to convert the stream into an IntStream.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.stream.IntStream; import java.util.stream.Stream; class Main { public static void main(String[] args) { Character[] chars = { 'T', 'e', 'c', 'h', 'i', 'e' }; // Convert `Character[]` to `IntStream` IntStream intStream = Stream.of(chars) .flatMapToInt(IntStream::of); intStream.forEach(System.out::println); } } |
Output:
84
101
99
104
105
101
That’s all about converting IntStream to Java String and vice versa.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)