stream and lambda(15) - 終止操作之 stream 陣列操作 toArray

語言: CN / TW / HK

在使用 Stream 的過程中,還是有不少場景需要將流內的元素轉成陣列。Stream 提供了兩個方法給我們將之轉為陣列。

  1. toArray()
  2. toArray(IntFunction<A[]> generator)

我就問一句,我能先說第二個嗎?

toArray(IntFunction<A[]> generator)

方法定義

<A> A[] toArray(IntFunction<A[]> generator)

方法傳入一個 IntFunction ,返回一個數組。 Function 我們前面講過,輸入一個引數,輸出一個引數。由於是 IntFunction<A[]> ,入參的型別限制為 int ,表示的含義是 流內元素的數量 ;返回結果是一個數組,這個陣列承載的內容就是流內元素的內容。

使用舉例

正常使用

public void toArrayWithFuncNormalTest() {
    Stream<String> stringStream = Stream.of("this", "is", "toArrayWithFuncTest");
    //String[]::new 等效於 size -> new String[size]
    String[] strings = stringStream.toArray(String[]::new);
    for (String str : strings) {
        System.out.print(str + " ");
    }
}

不出所料,程式正常輸出 this is toArrayWithFuncTest 。在這裡,我們提供的 IntFunction<A[]> 正確利用了流內元素的型別,也正確利用了流內元素的數量。

IntFunction 強行改變陣列大小會怎樣

public void toArrayWithFuncWrongSizeTest() {
    Stream<String> stringStream = Stream.of("this", "is", "toArrayWithFuncTest");
    String[] strings = stringStream.toArray(size -> new String[2]);
    for (String str : strings) {
        System.out.print(str + " ");
    }
}

程式執行異常,看來手動改返回的陣列大小是無用的。

java.lang.IllegalStateException: Begin size 3 is not equal to fixed size 2

IntFunction 強行改變陣列型別會怎樣

public void toArrayWithFuncWrongTypeTest() {
    Stream<String> stringStream = Stream.of("this", "is", "toArrayWithFuncTest");
    Integer[] nums = stringStream.toArray(Integer[]::new);
    for (Integer i : nums) {
        System.out.print(i + " ");
    }
}

程式同樣執行異常,看來傳入的型別和 Stream 元素的型別不一致也不行。

java.lang.ArrayStoreException: java.lang.String

toArray()

方法定義

Object[] toArray()

這個方法使用起來就比較簡單了,不用傳任何引數,返回一個 Object[] 陣列。其實看下實現就明白了。

public final Object[] toArray() {
    return toArray(Object[]::new);
}

直接呼叫了 toArray(IntFunction<A[]> generator) ,所以使用上應該不用多說了吧。

使用舉例

public void toArrayTest() {
    Stream<String> stringStream = Stream.of("this", "is", "toArrayTest");
    Object[] objects = stringStream.toArray();
    for (Object obj : objects) {
        System.out.print(obj + " ");
    }
}

程式正確輸出: this is toArrayTest