如何从数组创建流? [英] How can I create a stream from an array?

查看:41
本文介绍了如何从数组创建流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前每当我需要从数组创建流时,我都会

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 E.g.

You can use Arrays.stream E.g.

Arrays.stream(array);

您也可以使用@fge 提到的 Stream.of ,它看起来像

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) 将返回 StreamArrays.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时,会调用下面的代码

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 时,将调用以下代码

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.

更新:正如 Stuart Marks 评论所述Arrays.stream 的子范围重载优于使用 Stream.of(array).skip(n).limit(m) 因为前者导致 SIZED 流,而后者没有.原因是 limit(m) 不知道大小是 m 还是小于 m,而 Arrays.stream 进行范围检查并知道溪流你可以阅读Arrays.stream(array,start,end)返回的流实现源码这里,而对于 Stream.of(array).skip().limit() 位于 这个方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆