您好,登錄后才能下訂單哦!
引言
在 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
所以,推薦使用 Arrays.stream,不需要考慮是對象數(shù)組還是基本數(shù)組,直接返回對應(yīng)的流對象,操作方便。
源碼見:java-8-demo
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(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)容。