Java8如何将Array转换为Stream的实现代码
引言

创新互联是一家专业提供望江企业网站建设,专注与成都做网站、网站设计、外贸营销网站建设、H5场景定制、小程序制作等业务。10年已为望江众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。
在 java8 中,您可以使用 Arrays.Stream 或 Stream.of 将 Array 转换为 Stream。
1. 对象数组
对于对象数组,Arrays.stream 和 Stream.of 都返回相同的输出。
public static void main(String[] args) {
ObjectArrays();
}
private static void ObjectArrays() {
String[] array = {"a", "b", "c", "d", "e"};
//Arrays.stream
Stream stream = Arrays.stream(array);
stream.forEach(x-> System.out.println(x));
System.out.println("======");
//Stream.of
Stream stream1 = Stream.of(array);
stream1.forEach(x-> System.out.println(x));
}
输出:
a
b
c
d
e
======
a
b
c
d
e
查看 JDK 源码,对于对象数组,Stream.of 内部调用了 Arrays.stream 方法。
// Arrays public staticStream stream(T[] array) { return stream(array, 0, array.length); } // Stream public static Stream of(T... values) { return Arrays.stream(values); }
2. 基本数组
对于基本数组,Arrays.stream 和 Stream.of 将返回不同的输出。
public static void main(String[] args) {
PrimitiveArrays();
}
private static void PrimitiveArrays() {
int[] intArray = {1, 2, 3, 4, 5};
// 1. Arrays.stream -> IntStream
IntStream stream = Arrays.stream(intArray);
stream.forEach(x->System.out.println(x));
System.out.println("======");
// 2. Stream.of -> Stream
Stream temp = Stream.of(intArray);
// 不能直接输出,需要先转换为 IntStream
IntStream intStream = temp.flatMapToInt(x -> Arrays.stream(x));
intStream.forEach(x-> System.out.println(x));
}
输出:
1
2
3
4
5
======
1
2
3
4
5
查看源码,
// Arrays
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
// Stream
public static Stream of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
Which one
- 对于对象数组,两者都调用相同的 Arrays.stream 方法
- 对于基本数组,我更喜欢 Arrays.stream,因为它返回固定的大小 IntStream,更容易操作。
所以,推荐使用 Arrays.stream,不需要考虑是对象数组还是基本数组,直接返回对应的流对象,操作方便。
源码见:java-8-demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
文章题目:Java8如何将Array转换为Stream的实现代码
地址分享:http://www.jxjierui.cn/article/jiodcc.html


咨询
建站咨询
