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]);
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.
String str = "Geeks.for.Geeks" ; String[] arrOfStr = str.split( "[.]" ); // str.split("."); will give no output... Example 5: Java.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With