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?
You can use Java's
StringBuilder
type for this. There's alsoStringBuffer
, but it contains extra thread safety logic that is often unnecessary.If you are using Spring MVC then you can try following steps.
It will result to
a,b,c
Use an approach based on
java.lang.StringBuilder
! ("A mutable sequence of characters. ")Like you mentioned, all those string concatenations are creating Strings all over.
StringBuilder
won't do that.Why
StringBuilder
instead ofStringBuffer
? From theStringBuilder
javadoc:I would use Google Collections. There is a nice Join facility.
http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html
But if I wanted to write it on my own,
I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.
So basically something like this:
Use StringBuilder and class
Separator
Separator wraps a delimiter. The delimiter is returned by Separator's
toString
method, unless on the first call which returns the empty string!Source code for class
Separator