Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a String[] from Guava's Splitter

Tags:

java

string

guava

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]); 
like image 976
slipheed Avatar asked Sep 29 '11 20:09

slipheed


People also ask

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.

How do you create a split string in Java?

String str = "Geeks.for.Geeks" ; String[] arrOfStr = str.split( "[.]" ); // str.split("."); will give no output... Example 5: Java.

How do I split a string into whitespace characters?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.


1 Answers

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.

like image 178
Philipp Reichart Avatar answered Oct 31 '22 17:10

Philipp Reichart