The easiest way to transform collection to array?
To morph a Collection into an array, use toArray(T[] a)
. For our String friends for example:
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:
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:
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:
Stream API reshaping collections
For those complicated collection transformations, the Java 8 Stream API can act as your magic wand:
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:
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:
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:
Was this article helpful?