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 generalize it, but there's no join in Java, as you well say.
This might work better.
Why don't you do in Java the same thing you are doing in ruby, that is creating the delimiter separated string only after you've added all the pieces to the array?
You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...
Edit: fixed the order of appends.
Don't know if this really is any better, but at least it's using StringBuilder, which may be slightly more efficient.
Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.
You should probably use a
StringBuilder
with theappend
method to construct your result, but otherwise this is as good of a solution as Java has to offer.You could write a little join-style utility method that works on java.util.Lists
Then use it like so:
And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)