This post will discuss how to create a Stream of Characters from a primitive character array in Java.

Java provides the Stream, IntStream, LongStream, and DoubleStream classes to get streams over objects and the primitive int, long and double types. Java doesn’t provide char stream for primitive char. Therefore, we can’t apply Arrays.stream() method to a char[] array. However, we can get an IntStream (a stream of ints) of characters and use that to generate Stream<Characters>.

1. Using String object

A simple solution to get an IntStream of characters using the String.chars() method. After obtaining the IntStream of characters, box it to Stream<Character> by casting char using lambda expression i -> (char) i inside mapToObj() method.

Download  Run Code

Output:

[a, b, c, d]

2. Using IntStream.range()

Another alternative is to get IntStream of indices is using IntStream.range() method. After obtaining the IntStream, box it to Stream<Character> by casting char using lambda expression i -> chars[i] inside mapToObj() method.

Download  Run Code

Output:

[a, b, c, d]

3. Using CharBuffer.wrap() method

Another plausible way to create an IntStream from the primitive character array is to use CharBuffer. After obtaining the IntStream of characters, box it to Stream<Character> by casting char using lambda expression i -> (char) i inside mapToObj() method.

Download  Run Code

Output:

[a, b, c, d]

4. Using Guava’s Chars class

The idea here is to create a List of the boxed chars List<Character> and derive Stream<Character> from it. You can use Guava’s Chars.asList() method to wrap a primitive character array as a List<Character> type.

Download Code

Output:

[a, b, c, d]

5. Using Stream Builder

Finally, we can create a Stream Builder and add characters to it. Then use build() method to get a Stream<Character> from it.

Download  Run Code

Output:

[a, b, c, d]

That’s all about creating a Stream of Characters from a primitive character array in Java.