Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to create a stream of characters from char array in java

From a char array, I want to construct a stream to use java 8 features such as filters and maps.

char[] list = {'a','c','e'}; Stream<Character> cStream = Stream.of(list); // Stream<Character> cStream = Arrays.stream(list); 

The first method does not work (Reason: change cStream to Stream<char[]>). The commented line does not also work (Reason: The method stream(T[]) in the type Arrays is not applicable for the arguments (char[])).

I know that if char[] list is changed to int[], everything works fine using IntStream. But I do not want to convert every char[] to int[] each time or change into a list when I need to use stream library on char array.

like image 477
Sangjin Kim Avatar asked Jul 22 '15 04:07

Sangjin Kim


1 Answers

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]); 
like image 154
Alexis C. Avatar answered Oct 06 '22 04:10

Alexis C.