While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:
public String appendWithDelimiter( String original, String addition, String delimiter ) {
if ( original.equals( "" ) ) {
return addition;
} else {
return original + delimiter + addition;
}
}
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.
In Ruby, I can do something like this instead, which feels much more elegant:
parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
But since Java lacks a join command, I couldn't figure out anything equivalent.
So, what's the best way to do this in Java?
Why not write your own join() method? It would take as parameters collection of Strings and a delimiter String. Within the method iterate over the collection and build up your result in a StringBuffer.
You can try something like this:
The Google's Guava library has com.google.common.base.Joiner class which helps to solve such tasks.
Samples:
Here is an article about Guava's string utilities.
Java 8
For those who are in a Spring context their StringUtils class is useful as well:
There are many useful shortcuts like:
and many others.
This can be helpful if you are not already using Java 8 and you are already in a Spring context.
I prefer it against the Apache Commons (although very good as well) for the Collection support which is easier like this: