Creating a String[] from Guava's Splitter

slipheed picture slipheed · Sep 29, 2011 · Viewed 10.9k times · Source

Is there a more efficient way to create a string array from Guava's Splitter than the following?

Lists.newArrayList(splitter.split()).toArray(new String[0]);

Answer

Philipp Reichart picture Philipp Reichart · Sep 29, 2011

Probably not so much more efficient, but a lot clearer would be Iterables.toArray(Iterable, Class)

This pretty much does what you do already:

public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
    Collection<? extends T> collection = toCollection(iterable);
    T[] array = ObjectArrays.newArray(type, collection.size());
    return collection.toArray(array);
}

By using the collection.size() this should even be a tick faster than creating a zero-length array just for the type information and having toArray() create a correctly sized array from that.