Sean McMains Sean McMains - 1 year ago 79
Java Question

What's the best way to build a string of delimited items in Java?

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?

Answer Source

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:


Java 8:

Java 8 provides joining out of the box via StringJoiner and String.join(). The snippets below show how you can use them:


StringJoiner joiner = new StringJoiner(",");
String joinedString = joiner.toString(); // "01,02,03"

String.join(CharSequence delimiter, CharSequence... elements))

String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"

String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

List<String> strings = new LinkedList<>();
String message = String.join(" ", strings);
//message returned is: "Java is cool"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download