How to convert a Java 8 Stream to an Array?

To convert a Java 8 Stream to an array, you can use the toArray() method of the Stream interface. The toArray() method returns an array of the elements in the stream, and has two overloaded versions:

T[] toArray();
<A> A[] toArray(IntFunction<A[]> generator);

The first version returns an array of type Object[] and should be used if the stream elements are not of a specific type. The second version returns an array of the specified type and should be used if the stream elements are of a specific type.

Here are some examples of how to use the toArray() method to convert a stream to an array:

  1. Using the first version of the toArray() method:
Stream<String> stream = Stream.of("item1", "item2", "item3");
Object[] array = stream.toArray();  // array is ["item1", "item2", "item3"]
  1. Using the second version of the toArray() method:
Stream<String> stream = Stream.of("item1", "item2", "item3");
String[] array = stream.toArray(String[]::new);  // array is ["item1", "item2", "item3"]

Keep in mind that the toArray() method returns an array of type Object[] or of the specified type, depending on the version you use. If you need to convert the array to a different type, you can use the Arrays.copyOf() method or a manual loop to do the conversion.

For example, to convert an array of type Object[] to an array of type String[], you can use the following code:

Object[] objectArray = {"item1", "item2", "item3"};
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);