温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-08 19:57:10 来源:脚本之家 阅读:141 作者:火炎焱 栏目:编程语言

引言

在 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<String> stream = Arrays.stream(array);
 stream.forEach(x-> System.out.println(x));

 System.out.println("======");

 //Stream.of
 Stream<String> 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 static <T> Stream<T> stream(T[] array) {
 return stream(array, 0, array.length);
}

// Stream
public static<T> Stream<T> 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<int[]>
 Stream<int[]> 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<T> Stream<T> of(T t) {
 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

Which one

  • 对于对象数组,两者都调用相同的 Arrays.stream 方法
  • 对于基本数组,我更喜欢 Arrays.stream,因为它返回固定的大小 IntStream,更容易操作。

所以,推荐使用 Arrays.stream,不需要考虑是对象数组还是基本数组,直接返回对应的流对象,操作方便。

源码见:java-8-demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI