Java8 如何將 Array 轉換為 Stream


引言

在 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

系列文章詳見:Java 8 教程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM