想从java中的char数组创建一个字符流 [英] Want to create a stream of characters from char array in java
问题描述
从一个字符数组,我想构造一个流来使用 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
).注释行也不起作用(原因:数组类型中的方法 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屋!