本套JAVA8教程由于是有英文翻译过来的,如果有翻译不对的地方还请多多包涵。
本节课先简单的介绍下Java8有哪些新特性,对于Java6/7版本做出哪些更改.那废话不多说,赶紧开始今天的课程吧.
在Java 8里,你可以用Arrays.stream 或 Stream.of来将数组转换成流。
对象数组
- 对于对象数组,Arrays.stream 和 Stream.of方法都可以返回同样的输出结果。
例子:
public static void main(String[] args) {
String[] array = {"a", "b", "c", "d", "e"};
//Arrays.stream 调用
Stream stream1 = Arrays.stream(array);
stream1.forEach(System.out::println);
//Stream.of调用
Stream stream2 = Stream.of(array);
stream2.forEach(System.out::println);
}
请注意 对于对象数组,Stream.of方法会在内部调用Arrays.stream
原始数组
看下代码
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
// 1. Arrays.stream -> IntStream
IntStream intStream1 = Arrays.stream(intArray);
intStream1.forEach(System.out::println);
// 2. Stream.of ->; Stream
Stream temp = Stream.of(intArray);
// Cant print Stream directly, convert / flat it to IntStream
IntStream intStream2 = temp.flatMapToInt(Arrays::stream);
intStream2.forEach(System.out::println);
}
其实这样看并么有看到本质上的不同,那这次咱们看下源码实现吧
- 对象数组
Arrays.java
/**
* Returns a sequential {@link Stream} with the specified array as its
* source.
*
* @param 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 Stream stream(T[] array) {
return stream(array, 0, array.length);
}
Stream.java
/**
* Returns a sequential ordered stream whose elements are the specified values.
*
* @param 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 Stream of(T... values) {
return Arrays.stream(values);
}
从这我们不难看出对于对象数组,Stream.of方法会在内部调用Arrays.stream。
那下面咱们再看下原始数组的调用
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 the type of stream elements
* @return a singleton sequential stream
*/
public static Stream of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
该用哪一个呢?
对于对象数组,都会调用Arrays.stream(参见示例1,JDK源代码)。 对于原始数组,更推荐Arrays.stream,因为它直接返回固定大小的IntStream,更易于操作。
有不同意见的小伙伴们积极留言哦. 一起讨论!