Which method is used to convert a stream to an array?

Which method is used to convert a stream to an array?

a) toArray()
b) collect()
c) streamArray()
d) asArray()

Answer:

a) toArray()

Explanation:

The toArray() method is used to convert the elements of a stream into an array. This method is particularly useful when you need to perform operations that require an array, such as sorting or binary search, or when you need to pass the data to a method that accepts an array as a parameter. The toArray() method provides a simple way to transform a stream into an array without needing to manually collect and iterate over the elements.

By default, toArray() returns an Object[] array, but you can also provide an array generator function to specify the type of array you want to create. For example, you can use toArray(String[]::new) to create a String[] array from a stream of strings. This flexibility allows you to tailor the toArray() method to your specific needs, making it a versatile tool in the Stream API.

Since toArray() is a terminal operation, it consumes the stream and produces the resulting array. Once the array is created, the stream cannot be reused, and any further operations must be performed on the array itself. The toArray() method is often used in scenarios where you need to pass data from a stream to legacy code or APIs that expect arrays, making it a valuable method in Java development.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top