Collection.toArray()
Copies collection elements into an array.
Available since: Java 1.2
Syntax
Object[] toArray()
default <T> T[] toArray(IntFunction<T[]> generator)Parameters
| Parameter | Type | Description |
|---|---|---|
| generator | IntFunction<T[]> | Creates an array of the needed type, usually `String[]::new`. |
Return value
T[]A new array holding the collection elements.
Examples
An array of the needed type:
void main() {
List<String> names = List.of("Anna", "Oleg");
String[] arr = names.toArray(String[]::new);
IO.println(arr.length + " " + arr[1]);
IO.println(Arrays.toString(arr));
}Output:
2 Oleg
[Anna, Oleg]Notes
The no-argument version returns an Object[] that cannot be cast to String[]. So pass the generator String[]::new (Java 11) or an empty array: toArray(new String[0]). You cannot get a primitive array this way — for int[] use stream().mapToInt(Integer::intValue).toArray().
See also
Related recipes
In the tutorial
- Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.