当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。