流toArray()返回包含此流元素的數組。這是終端操作,即可能會遍曆流以產生結果或副作用。執行終端操作後,流管線被視為已消耗,無法再使用。
用法:
Object[] toArray()
返回值:該函數返回一個包含此流元素的數組。
示例1:
// Java code for Stream toArray()
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a Stream of Integers
Stream<Integer> stream = Stream.of(5, 6, 7, 8, 9, 10);
// Using Stream toArray()
Object[] arr = stream.toArray();
// Displaying the elements in array arr
System.out.println(Arrays.toString(arr));
}
}
輸出:
[5, 6, 7, 8, 9, 10]
示例2:
// Java code for Stream toArray()
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a Stream of Strings
Stream<String> stream = Stream.of("Geeks", "for",
"Geeks", "GeeksQuiz");
// Using Stream toArray()
Object[] arr = stream.toArray();
// Displaying the elements in array arr
System.out.println(Arrays.toString(arr));
}
}
輸出:
[Geeks, for, Geeks, GeeksQuiz]
示例3:
// Java code for Stream toArray()
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a Stream of Strings
Stream<String> stream = Stream.of("Geeks", "for",
"gfg", "GeeksQuiz");
// Using Stream toArray() and filtering
// the elements that starts with 'G'
Object[] arr = stream.filter(str
-> str.startsWith("G"))
.toArray();
// Displaying the elements in array arr
System.out.println(Arrays.toString(arr));
}
}
輸出:
[Geeks, GeeksQuiz]
相關用法
- Java IntStream toArray()用法及代碼示例
- Java SortedSet toArray()用法及代碼示例
- Java ArrayList toArray()用法及代碼示例
- Java DelayQueue toArray()用法及代碼示例
- Java Vector toArray()用法及代碼示例
- Java LinkedTransferQueue toArray()用法及代碼示例
- Java AbstractCollection toArray()用法及代碼示例
- Java Guava Booleans.toArray()用法及代碼示例
- Java Guava Bytes.toArray()用法及代碼示例
- Java Guava Floats.toArray()用法及代碼示例
- Java Guava Doubles.toArray()用法及代碼示例
- Java Guava Chars.toArray()用法及代碼示例
- Java Guava Shorts.toArray()用法及代碼示例
- Java Guava Longs.toArray()用法及代碼示例
- Java Stream map()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream toArray() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。