How To Split String in Java

There are various ways of splitting string in java using certain delimiter.

1. The most simple one is String.split() method:

String str = "World is wonderful";
String[] split = str.split(" ");
for (int i = 0; i < split.length; i++) {
   System.out.println(split[i]);
}

//Output:
World
is 
wonderful

2. Guava Splitter.split()

String str = "World is wonderfull";
Iterable split = Splitter.on(' ').split(str);
split.forEach(System.out::println);

//Output:
World
is 
wonderful

3. ApacheCommons StringUtils.split()

 
String str = "World is wonderfull";
String[] split = StringUtils.split(str, ' ');
for (int i = 0; i < split.length; i++) {
   System.out.println(split[i]);
}

//Output:
World
is 
wonderful
[addToAppearHere]

Let’s compare the performance for a different size of input tokens. Consider two cases when str contains
A. 10000 tokens
B. 10000000 tokens

//Java String.split()
long start = System.currentTimeMillis();
String[] splitJava = str.split(",");
for (int i = 0; i < splitJava.length; i++) {
   splitJava[i].length();
}
long end = System.currentTimeMillis();
System.out.println("Java String#split time = " + (end - start) +"ms");
//Guava Splitter.split()
start = System.currentTimeMillis();
Iterable split = Splitter.on(',').split(str);
for (String s : split) {
   s.length();
}
end = System.currentTimeMillis();
System.out.println("Guava Splitter.split() time = " + (end - start) + "ms");
//Apache Commons StringUtils.split()
start = System.currentTimeMillis();
splitJava = StringUtils.split(str, ',');
for (int i = 0; i < splitJava.length; i++) {
   splitJava[i].length();
}
end = System.currentTimeMillis();
System.out.println("Apache StringUtils.split() time = " + (end - start) + "ms");

For case A. (10000 tokens) will have the following output

Java String.split() time = 8ms
Guava Splitter.split() time = 47ms
Apache StringUtils.split() time = 11ms

For case B. (10000000):

Java String.split() time = 16153ms
Guava Splitter.split() time = 1149ms
Apache StringUtils.split() time = 8391ms

So for small number of tokens String.split() and StringUtils.split() are faster, but for big number of tokens Guava’s Splitter.split() shows better performance.