The easiest way to transform collection to array? The easiest way to transform collection to array? arrays arrays

The easiest way to transform collection to array?


Where x is the collection:

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


Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()    .map(x -> new Bar(x))    .toArray(size -> new Bar[size]);


If you use it more than once or in a loop, you could define a constant

public static final Foo[] FOO = new Foo[]{};

and do the conversion it like

Foo[] foos = fooCollection.toArray(FOO);

The toArray method will take the empty array to determine the correct type of the target array and create a new array for you.


Here's my proposal for the update:

Collection<Foo> foos = new ArrayList<Foo>();Collection<Bar> temp = new ArrayList<Bar>();for (Foo foo:foos)     temp.add(new Bar(foo));Bar[] bars = temp.toArray(new Bar[]{});