Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collection.toArray()

Copies collection elements into an array.

Available since: Java 1.2

Syntax

Object[] toArray()
default <T> T[] toArray(IntFunction<T[]> generator)

Parameters

ParameterTypeDescription
generatorIntFunction<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

  • List.of() — Creates an unmodifiable list from the listed elements.
  • ArrayList — A resizable list backed by an array — the most common `List` implementation.

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.

Thanks for reading!

Donate to the site — we work hard for you.