當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stream toArray()用法及代碼示例


流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]


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream toArray() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。