如何创建从一个数组流? [英] How can I create a stream from an array?
问题描述
目前,每当我需要从阵列中创建的流,我
Currently whenever I need to create stream from an array, I do
String[] array = {"x1", "x2"};
Arrays.asList(array).stream();
有一些直接的方式来从一个数组创建流?
Is there some direct way to create stream from an array?
推荐答案
您可以使用Arrays.stream例如
You can use Arrays.stream E.g.
Arrays.stream(array);
您也可以使用 Stream.of
由@fge,它看起来像
You can also use Stream.of
as mentioned by @fge , which looks like
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
不过需要注意的 Stream.of(intArray)
将返回流&LT; INT []&GT;
,而 Arrays.stream(将intArr)
将返回 IntStream
为您传递类型的数组 INT []
。所以,简而言之为基元类型你可以观察到两种方法之间的差异例如
But note Stream.of(intArray)
will return Stream<int[]>
whereas Arrays.stream(intArr)
will return IntStream
providing you pass an array of type int[]
. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.
int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);
IntStream stream2 = Arrays.stream(arr);
当你传递的原始数组 Arrays.stream
,以下code调用
When you pass primitive array to Arrays.stream
, the following code is invoked
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
和当你通过基本数组为 Stream.of
以下code调用
and when you pass primitive array to Stream.of
the following code is invoked
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
因此,你会得到不同的结果。
Hence you get different results.
更新:由于斯图尔特商标评论中提及 Arrays.stream
的子范围过载为preferable使用 Stream.of(阵列).skip(N).limit(M)
因为在指定大小的数据流,而后者前者的结果没有。其原因是,限制(M)
不知道尺寸是否是M或小于M,而 Arrays.stream
确实范围检查和知道流的确切大小
你可以阅读源$ C $ C由返回流实现Arrays.stream(数组,开始,结束)
here,而对于Stream.of(阵列).skip()由返回流实现。限制()
是在<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/8-b132/java/util/stream/SliceOps.java#SliceOps.makeRef%28java.util.stream.AbstractPipeline%2Clong%2Clong%29\">this方法。
Updated: As mentioned by Stuart Marks comment
The subrange overload of Arrays.stream
is preferable to using Stream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is that limit(m)
doesn't know whether the size is m or less than m, whereas Arrays.stream
does range checks and knows the exact size of the stream
You can read the source code for stream implementation returned by Arrays.stream(array,start,end)
here, whereas for stream implementation returned by Stream.of(array).skip().limit()
is within this method.
这篇关于如何创建从一个数组流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!