想要在java中从char数组创建一个字符流 [英] Want to create a stream of characters from char array in java
问题描述
从char数组中,我想构建一个流来使用java 8等功能,例如过滤器和地图。
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);
第一种方法不起作用(原因:将cStream更改为 Stream< char []>
)。
注释行也不起作用(原因:Arrays类型中的方法 stream(T [])
不适用于参数( char []
))。
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[]
)).
我知道如果 char [] list
更改为 int []
,使用 IntStream
,一切正常。但是我不希望每次将每个 char []
转换为 int []
,或者当我改为列表时需要在 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.
推荐答案
您可以使用 IntStream
生成索引,然后按 mapToObj
:
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]);
这篇关于想要在java中从char数组创建一个字符流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!