Explain Codes LogoExplain Codes Logo

The easiest way to transform collection to array?

java
stream-api
java-8
collections
Alex KataevbyAlex Kataev·Mar 8, 2025
TLDR

To morph a Collection into an array, use toArray(T[] a). For our String friends for example:

Collection<String> collection = Arrays.asList("apple", "banana", "cherry"); String[] array = collection.toArray(new String[0]);

This one-liner adapts the array size to snugly fit the collection. Just swap out String with the specific type you’re handling.

Transmogrifying mismatched types

When you’re playing Dr Frankenstein with a Collection<Foo> to a Bar[] array (where Foo and Bar are creature types err.. different types), use streams à la Java 8:

Collection<Foo> foos = //... your collection Bar[] bars = foos.stream().map(foo -> new Bar(foo)).toArray(Bar[]::new); //it’s alive!

Here the map feature helps transform each Foo creature... ahem element into a new Bar type, collecting the ensemble into an array.

Enforcing type safety

To keep things crisp and ensure there’s no type mismatch in your monster mash-up, specify the array type crystal clear:

Foo[] foos = fooCollection.toArray(new Foo[fooCollection.size()]);

This move checkmates any potential ClassCastException by using the right array type in the transformation process.

Libraries to the rescue

Guava's Iterables provides a nifty hack, letting you convert types without mentioning the size:

Foo[] foos = Iterables.toArray(fooCollection, Foo.class);

Stream API reshaping collections

For those complicated collection transformations, the Java 8 Stream API can act as your magic wand:

Collection<Foo> collection = //... Bar[] array = collection.stream() .map(foo -> new Bar(foo)) .toArray(Bar[]::new); // poof! And it’s done.

This can flex some serious muscles for collection reshaping and custom object creation.

What's under toArray's hood?

Interesting fact! toArray() method performs better as it may use Arrays.copyOf() under the hood.

Extracting efficiency with constructors

Did you know, since JDK 11, you’ve been able to utilize toArray(IntFunction<T[]> generator) for concise array conversion:

Foo[] array = fooCollection.toArray(Foo[]::new); // As clean as new shoes.

Implementation of constructor references in toArray? Check! Efficient type array construction? Check!

Beware of the toArray(null)

Steer clear of toArray(null), a classic prankster move which may result in compilation issues. Always specify an array when invoking toArray.

Array recyclability for reduction

What to do if you’re dealing with transformations time and again? Reuse a constant array:

private static final Foo[] EMPTY_FOO_ARRAY = new Foo[0]; // Yep, it's clean :) // later in code Foo[] foos = fooCollection.toArray(EMPTY_FOO_ARRAY); // Like reusing a coffee mug!

This reduces memory consumption by not creating new beasts... err array instances for every transformation.

Looping for non-list collections

If your collection isn’t a list, say an ArrayList, and you relish a good loop for a transformation, try this:

Collection<Foo> foos = new HashSet<>(); Foo[] fooArray = new Foo[foos.size()]; int i = 0; for (Foo foo : foos) { fooArray[i++] = foo; // Round and round she goes, where she stops nobody knows }