在Java8中,你可以使用Arrays.stream
或Stream.of
来把数组转为Stream。
1. 对象数组
对于对象数组,Arrays.stream
和Stream.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));
}
}
输出
a
b
c
d
e
a
b
c
d
e
查看JDK的源码后,你会发现Stream.of
的内部实际上也是调用Arrays.stream
方法。
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);
}
2. 原始类型数组
对应原始类型数组,Arrays.stream
和Stream.of
将会返回不同的结果。
TestJava8.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class TestJava8 {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
// 1. Arrays.stream 返回 IntStream
IntStream intStream1 = Arrays.stream(intArray);
intStream1.forEach(x -> System.out.println(x));
// 2. Stream.of 返回 Stream<int[]>
Stream<int[]> temp = Stream.of(intArray);
// 使用flatMapToInt展开Stream<int[]>
IntStream intStream2 = temp.flatMapToInt(x -> Arrays.stream(x));
intStream2.forEach(x -> System.out.println(x));
}
}
输出
1
2
3
4
5
1
2
3
4
5
通过查看JDK源码可以发现,此时Arrays.stream
调用的是重载函数Arrays.stream(int[] array)
。
Arrays.java
/**
* Returns a sequential {@link IntStream} with the specified array as its
* source.
*
* @param array the array, assumed to be unmodified during use
* @return an {@code IntStream} for the array
* @since 1.8
*/
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
Stream.java
/**
* Returns a sequential {@code Stream} containing a single element.
*
* @param t the single element
* @param <T> the type of stream elements
* @return a singleton sequential stream
*/
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}