Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any generic version of toArray() in Guava or Apache Commons Collections?

What I'm looking for is a generic version of Object[] java.util.Collection.toArray() or a less verbose alternative to using T[] java.util.Collection.toArray(T[] array). I can currently write:

Collection<String> strings;
String[] array = strings.toArray(new String[strings.size()]);

What I'm looking for is something like:

@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> collection, Class<T> clazz) {
    return collection.toArray((T[]) Array.newInstance(clazz, collection.size()));
}

which I can then use as:

String[] array = Util.toArray(strings, String.class);

So is anything like this implemented in Guava or in Commons Collections?

Of course I can write my own (the above), which seems to be as fast as toArray(T[] array).

like image 842
Mihai Avatar asked Feb 12 '14 13:02

Mihai


2 Answers

Iterables.toArray() from Guava.

like image 58
axtavt Avatar answered Nov 15 '22 00:11

axtavt


You can shorten it with

String[] array = strings.toArray(new String[0]);

which also happens to be more efficient.

With Java 8 you can also use this, but it seems unnecessarily complicated and is probably slower:

String[] array = strings.stream().toArray(String[]::new);     // Java 8
like image 12
assylias Avatar answered Nov 14 '22 23:11

assylias