stream and lambda(15) - 終止操作之 stream 陣列操作 toArray
在使用 Stream 的過程中,還是有不少場景需要將流內的元素轉成陣列。Stream 提供了兩個方法給我們將之轉為陣列。
- toArray()
- 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
。
「其他文章」
- stream and lambda(18) - 終止操作之 stream 收集器 collectors
- stream and lambda(15) - 終止操作之 stream 陣列操作 toArray
- stream and lambda(13) - 終止操作之計數 count 與比較 min、max
- stream and lambda(12) - 終止操作之查詢與匹配(findAny、findFirst、allMatch、anyMatch、noneMatch)
- stream and lambda(11) - Optional 簡介
- stream and lambda(10) - 中間操作之排序sorted與除錯peek
- stream and lambda(9) - 中間操作之map操作(map、flatmap)
- stream and lambda(8) - 中間操作之篩選操作(filter、distinct、limit、skip)
- stream and lambda(7) - stream 的建立
- stream and lambda(6) - stream 簡介
- stream and lambda(5) - lambda 表示式最佳實踐
- stream and lambda(3) - jdk 提供的函式式介面
- stream and lambda(2) - 函式式介面簡介
- stream and lambda(1) - lambda 簡介