Want to create a stream of characters from char array in java
You can use an IntStream
to generate the indices followed by mapToObj
:
char[] arr = {'a','c','e'};
Stream<Character> cStream = IntStream.range(0, arr.length).mapToObj(i -> arr[i]);
A way to do this is via a String object:
char[] list = {'a','c','e'};
Stream<Character> charStream = new String(list).chars().mapToObj(i->(char)i);
I like to do it this way because all the complexity of transforming the array is wrapped into the String creation, and the wrapping of char is also performed behind the scene for me so I can focus on the business logic.
A short and efficient way to create an IntStream
from char[]
array is to use java.nio.CharBuffer
:
char[] list = {'a','c','e'};
IntStream stream = CharBuffer.wrap(list).chars();
This way you can use an IntStream
interpreting the int values as characters. If you want a boxed Stream<Character>
(which may be less efficient), use
Stream<Character> stream = CharBuffer.wrap(list).chars().mapToObj(ch -> (char)ch);
Using CharBuffer
can be a little bit faster than IntStream.range
as it has custom spliterator inside, so it does not have to execute an additional lambda (possibly as slow polymorphic call). Also it refers to the char[]
array only once and not inside the lambda, so it can be used with non-final array variable or function return value (like CharBuffer.wrap(getCharArrayFromSomewhere()).chars()
).