Arrays due to fast execution consumes more memory and has better performance. Collections, on the other hand, consume less memory but also have low performance as compared to Arrays. Arrays can hold the only the same type of data in its collection i.e only homogeneous data types elements are allowed in case of arrays.
The best and easiest way to convert a List into an Array in Java is to use the . toArray() method. Likewise, we can convert back a List to Array using the Arrays. asList() method.
To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T… a) that converts the array into a Collection.
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[]{});
With JDK/11, an alternate way of converting a Collection<Foo>
to an Foo[]
could be to make use of Collection.toArray(IntFunction<T[]> generator)
as:
Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11
As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0])
--
The upshot is that implementations that use
Arrays.copyOf(
) are the fastest, probably because it's an intrinsic.It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.
The implementation of the API within the JDK reads:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
The default implementation calls
generator.apply(0)
to get a zero-length array and then simply callstoArray(T[])
. This goes through theArrays.copyOf()
fast path, so it's essentially the same speed astoArray(new T[0])
.
Note:- Just that the API use shall be guided along with a backward incompatibility when used for code with null
values e.g. toArray(null)
since these calls would now be ambiguous because of existing toArray(T[] a)
and would fail to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With