java.util.Arrays.stream() 方法返回一个顺序 Stream,其指定数组的指定范围作为其源。
语法
public static <T> Stream<T> stream(T[] array,
int startInclusive,
int endExclusive)
这里,T 是数组中元素的类型。
参数
array | 指定数组,假定在使用过程中未修改。 |
startInclusive | 指定要覆盖的第一个索引(包括)。 |
endExclusive | 指定紧接着最后一个索引之后的索引要覆盖的索引。 |
返回值
返回数组范围的流。
异常
如果 startInclusive 为负数、endExclusive 小于 startInclusive 或 endExclusive 大于数组大小,则抛出 ArrayIndexOutOfBoundsException。
示例:
在下面的示例中,java.util.Arrays.stream() 方法返回一个顺序 Stream,以给定数组的指定范围作为其源。
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String[] args) {
//创建一个整数数组
Integer[] Arr = {1, 2, 3, 4, 5};
//通过转换创建Stream对象
//将数组的范围[2,5)放入流中
Stream<Integer> stream = Arrays.stream(Arr, 2, 5);
//打印流
System.out.print("The stream contains: ");
stream.forEach(str -> System.out.print(str + " "));
}
}
上述代码的输出将是:
The stream contains: 3 4 5