📜  使用示例在Java中流式传输 toArray()

📅  最后修改于: 2022-05-13 01:55:17.102000             🧑  作者: Mango

使用示例在Java中流式传输 toArray()

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