Java.Collections.How to copy elements of any collection to an array in one line?

✅ If you want to copy elements from any collection to an array in just one line, here’s how you do it in Java:


🧾 Syntax (Java 11+ recommended):

Object[] array = collection.toArray();

This gives you a plain Object[] array — works with any Collection.


🧠 If you want a typed array (e.g. String[], Integer[]), use this one-liner:

String[] array = list.toArray(new String[0]);
  • The new String[0] is a type hint.
  • Java will create a new array of the correct size and type.
  • This works with any type-safe collection.

✅ Examples:

List to array:

List<String> list = List.of("apple", "banana", "cherry");
String[] array = list.toArray(new String[0]); // one-liner

Set to array:

Set<Integer> set = Set.of(1, 2, 3);
Integer[] array = set.toArray(new Integer[0]);

🚀 Java 16+ alternative using streams:

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

But the toArray(new T[0]) approach is still preferred for simplicity and performance.

🧠 TL;DR

GoalOne-liner
Object[] arraycollection.toArray()
Typed array (e.g. String[])collection.toArray(new String[0])
This entry was posted in Без рубрики. Bookmark the permalink.