从Guava的Splitter创建一个String []

时间:2011-09-29 20:19:03

标签: java string guava

是否有更有效的方法从Guava's Splitter创建字符串数组而不是以下内容?

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

2 个答案:

答案 0 :(得分:27)

可能效率不是那么高,但更明确的是Iterables.toArray(Iterable, Class)

这几乎可以帮到你做的事情:

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

通过使用collection.size(),这甚至比为类型信息创建零长度数组更快,并且toArray()从中创建正确大小的数组。

答案 1 :(得分:17)

怎么样

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

因为有Iterables.toArray()方法