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?
using Dollar is simple as typing:
NB: it works also for Array and other data types
Implementation
Internally it uses a very neat trick:
the class
Separator
return the empty String only the first time that it is invoked, then it returns the separator:Pre Java 8:
Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:
StringUtils.join(java.lang.Iterable,char)
Java 8:
Java 8 provides joining out of the box via
StringJoiner
andString.join()
. The snippets below show how you can use them:StringJoiner
String.join(CharSequence delimiter, CharSequence... elements))
String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
in Java 8 you can do this like:
if list has nulls you can use:
In Java 8 you can use
String.join()
:Also have a look at this answer for a Stream API example.
With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:
Instead of using string concatenation, you should use StringBuilder if your code is not threaded, and StringBuffer if it is.