Java 如何将Array转换为Stream

来源:互联网 发布:ti高频电压注入源码 编辑:程序博客网 时间:2024/05/16 06:18

Java 如何将Array转换为Stream

在Java 8中,您可以使用Arrays.streamStream.of将Array转换为Stream
对于Objects Array,Arrays.streamStream.of返回相同的输出
TestJava8.java
package com.mkyong.java8;import java.util.Arrays;import java.util.stream.Stream;public class TestJava8 {    public static void main(String[] args) {        String[] array = {"a", "b", "c", "d", "e"};        //Arrays.stream        Stream<String> stream1 = Arrays.stream(array);        stream1.forEach(x -> System.out.println(x));        //Stream.of        Stream<String> stream2 = Stream.of(array);        stream2.forEach(x -> System.out.println(x));    }}

Output

a b c d e a b c d e

查看JDK源代码

Arrays.java
/**  * Returns a sequential {@link Stream} with the specified array as its  * source.  *  * @param <T> The type of the array elements  * @param array The array, assumed to be unmodified during use  * @return a {@code Stream} for the array  * @since 1.8  */ public static <T> Stream<T> stream(T[] array) {     return stream(array, 0, array.length); }
Stream.java
/**  * Returns a sequential ordered stream whose elements are the specified values.  *  * @param <T> the type of stream elements  * @param values the elements of the new stream  * @return the new stream  */ @SafeVarargs @SuppressWarnings("varargs") // Creating a stream from an array is safe public static<T> Stream<T> of(T... values) {     return Arrays.stream(values); }
注意
对于对象数组,该Stream.of方法在内部调用Arrays.stream

原创粉丝点击