溫馨提示×

溫馨提示×

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

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

Java8中怎么將Array轉(zhuǎn)換為Stream

發(fā)布時(shí)間:2021-07-24 14:52:20 來源:億速云 閱讀:221 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)Java8中怎么將Array轉(zhuǎn)換為Stream,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

1. 對(duì)象數(shù)組

對(duì)于對(duì)象數(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)); }

輸出:

abcde======abcde

查看 JDK 源碼,對(duì)于對(duì)象數(shù)組,Stream.of 內(nèi)部調(diào)用了 Arrays.stream 方法。

// Arrayspublic static <T> Stream<T> stream(T[] array) {  return stream(array, 0, array.length);}// Streampublic static<T> Stream<T> of(T... values) {  return Arrays.stream(values);}

2. 基本數(shù)組

對(duì)于基本數(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)); }

輸出:

12345======12345

查看源碼,

// Arrayspublic static IntStream stream(int[] array) {  return stream(array, 0, array.length);}// Streampublic static<T> Stream<T> of(T t) {  return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);}

Which one

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

以上就是Java8中怎么將Array轉(zhuǎn)換為Stream,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

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

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

AI