Creating an Array from a Collection

suggest change

Two methods in java.util.Collection create an array from a collection:

Object[] toArray() can be used as follows:

Set<String> set = new HashSet<String>();
set.add("red");
set.add("blue");

// although set is a Set<String>, toArray() returns an Object[] not a String[]
Object[] objectArray = set.toArray();

<T> T[] toArray(T[] a) can be used as follows:

Set<String> set = new HashSet<String>();
set.add("red");
set.add("blue");

// The array does not need to be created up front with the correct size.
// Only the array type matters. (If the size is wrong, a new array will
// be created with the same type.)
String[] stringArray = set.toArray(new String[0]);  

// If you supply an array of the same size as collection or bigger, it
// will be populated with collection values and returned (new array
// won't be allocated)
String[] stringArray2 = set.toArray(new String[set.size()]);

The difference between them is more than just having untyped vs typed results. Their performance can differ as well (for details please read this performance analysis section):

Starting from Java SE 8+, where the concept of Stream has been introduced, it is possible to use the Stream produced by the collection in order to create a new Array using the Stream.toArray method.

String[] strings = list.stream().toArray(String[]::new);

Examples taken from two answers (1, 2) to Converting ’ArrayList to ‘String[]’ in Java on Stack Overflow.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents