Iterables.toArray()
from Guava.
Is there any generic version of toArray() in Guava or Apache Commons Collections?
-
10-10-2022 - |
题
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).
解决方案
其他提示
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
不隶属于 StackOverflow