溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java8如何將Array轉(zhuǎn)換為Stream的實(shí)現(xiàn)代碼

發(fā)布時間:2020-09-08 19:57:10 來源:腳本之家 閱讀:152 作者:火炎焱 欄目:編程語言

引言

在 java8 中,您可以使用 Arrays.Stream 或 Stream.of 將 Array 轉(zhuǎn)換為 Stream。

1. 對象數(shù)組

對于對象數(shù)組,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 源碼,對于對象數(shù)組,Stream.of 內(nèi)部調(diào)用了 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. 基本數(shù)組

對于基本數(shù)組,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);

 // 不能直接輸出,需要先轉(zhuǎn)換為 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

  • 對于對象數(shù)組,兩者都調(diào)用相同的 Arrays.stream 方法
  • 對于基本數(shù)組,我更喜歡 Arrays.stream,因?yàn)樗祷毓潭ǖ拇笮?IntStream,更容易操作。

所以,推薦使用 Arrays.stream,不需要考慮是對象數(shù)組還是基本數(shù)組,直接返回對應(yīng)的流對象,操作方便。

源碼見:java-8-demo

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI