slipheed
slipheed

Reputation: 7278

Creating a String[] from Guava's Splitter

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]);

Upvotes: 26

Views: 11530

Answers (2)

Philipp Reichart
Philipp Reichart

Reputation: 20961

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.

Upvotes: 27

Jason S
Jason S

Reputation: 189696

How about

Iterables.toArray(splitter.split(), String.class);

since there's an Iterables.toArray() method

Upvotes: 17

Related Questions