[JAVA] Arrays.stream()和Stream.of的区别

以下是stream()的签名:

public static Stream of(T t)
public static Stream of(T… values)

以下是of()的签名(部分):

public static  Stream stream(T[] array)
public static  Stream stream(T[] array, int startInclusive, int endExclusive)
public static IntStream stream(int[] array)
...
public static DoubleStream stream(double[] array)
public static DoubleStream stream(double[] array, int startInclusive, int endExclusive)

其中一个重要的区别就是传入诸如

new int[]{1, 2}

之类的变量时,两者返回的实例不同,以以上变量为例子,of(new int[]{1, 2})返回的是Stream<int[]>(注意不是Stream<Integer>);stream(new int[]{1, 2})返回的则是IntStream。

在传入基本类型数组时需要格外注意。

另外stream()不支持char数组作参数。

另外一个区别就是,直接往stream()传入数量不定的基本类型参数时(例:stream(1, 2, 3)),IDE会直接报错(参数不适用),而往of()中传入则会生成对应的流(比如之前举的例子生成的是Stream<Integer>)。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据