<p>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:</p>

<pre><code>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", "," );
</code></pre>

<p>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.</p>

<p>In Ruby, I can do something like this instead, which feels much more elegant:</p>

<pre><code>parameterArray = [];
parameterArray &lt;&lt; "elementName" if condition;
parameterArray &lt;&lt; "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
</code></pre>

<p>But since Java lacks a join command, I couldn't figure out anything equivalent.</p>

<p>So, what's the best way to do this in Java?</p>

[{'answer_id': 63173, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 4, 'selected': False, 'text': '<p>Use an approach based on <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html" rel="noreferrer"><code>java.lang.StringBuilder</code></a>!  ("A mutable sequence of characters. ")</p>\n\n<p>Like you mentioned, all those string concatenations are creating Strings all over.  <code>StringBuilder</code> won\'t do that.</p>\n\n<p>Why <code>StringBuilder</code> instead of <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html" rel="noreferrer"><code>StringBuffer</code></a>?  From the <code>StringBuilder</code> javadoc:</p>\n\n<blockquote>\n  <p>Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. </p>\n</blockquote>\n'}, {'answer_id': 63186, 'author': 'Kent Boogaart', 'author_id': 5380, 'author_profile': 'https://Stackoverflow.com/users/5380', 'pm_score': 2, 'selected': False, 'text': '<p>You can use Java\'s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html" rel="nofollow noreferrer"><code>StringBuilder</code></a> type for this. There\'s also <code>StringBuffer</code>, but it contains extra thread safety logic that is often unnecessary.</p>\n'}, {'answer_id': 63191, 'author': 'Dave Costa', 'author_id': 6568, 'author_profile': 'https://Stackoverflow.com/users/6568', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 63201, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 4, 'selected': False, 'text': '<p>You can generalize it, but there\'s no join in Java, as you well say.</p>\n\n<p><a href="http://snippets.dzone.com/posts/show/91" rel="noreferrer">This</a> might work better. </p>\n\n<pre><code>public static String join(Iterable&lt;? extends CharSequence&gt; s, String delimiter) {\n    Iterator&lt;? extends CharSequence&gt; iter = s.iterator();\n    if (!iter.hasNext()) return "";\n    StringBuilder buffer = new StringBuilder(iter.next());\n    while (iter.hasNext()) buffer.append(delimiter).append(iter.next());\n    return buffer.toString();\n}\n</code></pre>\n'}, {'answer_id': 63217, 'author': 'martinatime', 'author_id': 1353, 'author_profile': 'https://Stackoverflow.com/users/1353', 'pm_score': 0, 'selected': False, 'text': '<p>You can try something like this:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nif (condition) { sb.append("elementName").append(","); }\nif (anotherCondition) { sb.append("anotherElementName").append(","); }\nString parameterString = sb.toString();\n</code></pre>\n'}, {'answer_id': 63218, 'author': 'izb', 'author_id': 974, 'author_profile': 'https://Stackoverflow.com/users/974', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public static String join(String[] strings, char del)\n{\n    StringBuffer sb = new StringBuffer();\n    int len = strings.length;\n    boolean appended = false;\n    for (int i = 0; i &lt; len; i++)\n    {\n        if (appended)\n        {\n            sb.append(del);\n        }\n        sb.append(""+strings[i]);\n        appended = true;\n    }\n    return sb.toString();\n}\n</code></pre>\n'}, {'answer_id': 63226, 'author': 'newdayrising', 'author_id': 3126, 'author_profile': 'https://Stackoverflow.com/users/3126', 'pm_score': 1, 'selected': False, 'text': '<p>You should probably use a <code>StringBuilder</code> with the <code>append</code> method to construct your result, but otherwise this is as good of a solution as Java has to offer.</p>\n'}, {'answer_id': 63229, 'author': 'agnul', 'author_id': 6069, 'author_profile': 'https://Stackoverflow.com/users/6069', 'pm_score': 1, 'selected': False, 'text': '<p>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?</p>\n\n<pre><code>ArrayList&lt;String&gt; parms = new ArrayList&lt;String&gt;();\nif (someCondition) parms.add("someString");\nif (anotherCondition) parms.add("someOtherString");\n// ...\nString sep = ""; StringBuffer b = new StringBuffer();\nfor (String p: parms) {\n    b.append(sep);\n    b.append(p);\n    sep = "yourDelimiter";\n}\n</code></pre>\n\n<p>You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...</p>\n\n<p><em>Edit</em>: fixed the order of appends.</p>\n'}, {'answer_id': 63258, 'author': 'Martin Gladdish', 'author_id': 7686, 'author_profile': 'https://Stackoverflow.com/users/7686', 'pm_score': 10, 'selected': True, 'text': '<h3>Pre Java 8:</h3>\n\n<p>Apache\'s commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: </p>\n\n<p><a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char)" rel="noreferrer"><code>StringUtils.join(java.lang.Iterable,char)</code></a></p>\n\n<hr>\n\n<h3>Java 8:</h3>\n\n<p>Java 8 provides joining out of the box via <code>StringJoiner</code> and <code>String.join()</code>. The snippets below show how you can use them:</p>\n\n<p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html" rel="noreferrer"><code>StringJoiner</code></a></p>\n\n<pre><code>StringJoiner joiner = new StringJoiner(",");\njoiner.add("01").add("02").add("03");\nString joinedString = joiner.toString(); // "01,02,03"\n</code></pre>\n\n<hr>\n\n<p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-" rel="noreferrer"><code>String.join(CharSequence delimiter, CharSequence... elements))</code></a></p>\n\n<pre><code>String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06"\n</code></pre>\n\n<hr>\n\n<p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-" rel="noreferrer"><code>String.join(CharSequence delimiter, Iterable&lt;? extends CharSequence&gt; elements)</code></a></p>\n\n<pre><code>List&lt;String&gt; strings = new LinkedList&lt;&gt;();\nstrings.add("Java");strings.add("is");\nstrings.add("cool");\nString message = String.join(" ", strings);\n//message returned is: "Java is cool"\n</code></pre>\n'}, {'answer_id': 63274, 'author': 'Rob Dickerson', 'author_id': 7530, 'author_profile': 'https://Stackoverflow.com/users/7530', 'pm_score': 6, 'selected': False, 'text': '<p>You could write a little join-style utility method that works on java.util.Lists</p>\n\n<pre><code>public static String join(List&lt;String&gt; list, String delim) {\n\n    StringBuilder sb = new StringBuilder();\n\n    String loopDelim = "";\n\n    for(String s : list) {\n\n        sb.append(loopDelim);\n        sb.append(s);            \n\n        loopDelim = delim;\n    }\n\n    return sb.toString();\n}\n</code></pre>\n\n<p>Then use it like so:</p>\n\n<pre><code>    List&lt;String&gt; list = new ArrayList&lt;String&gt;();\n\n    if( condition )        list.add("elementName");\n    if( anotherCondition ) list.add("anotherElementName");\n\n    join(list, ",");\n</code></pre>\n'}, {'answer_id': 63282, 'author': 'killdash10', 'author_id': 7621, 'author_profile': 'https://Stackoverflow.com/users/7621', 'pm_score': 0, 'selected': False, 'text': '<p>So basically something like this:</p>\n\n<pre><code>public static String appendWithDelimiter(String original, String addition, String delimiter) {\n\nif (original.equals("")) {\n    return addition;\n} else {\n    StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());\n        sb.append(original);\n        sb.append(delimiter);\n        sb.append(addition);\n        return sb.toString();\n    }\n}\n</code></pre>\n'}, {'answer_id': 63305, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://commons.apache.org/" rel="noreferrer">Apache commons</a> StringUtils class has a join method.</p>\n'}, {'answer_id': 63306, 'author': 'Mikezx6r', 'author_id': 5382, 'author_profile': 'https://Stackoverflow.com/users/5382', 'pm_score': 0, 'selected': False, 'text': '<p>Don\'t know if this really is any better, but at least it\'s using StringBuilder, which may be slightly more efficient.</p>\n\n<p>Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.</p>\n\n<pre><code>// Answers real question\npublic String appendWithDelimiters(String delimiter, String original, String addition) {\n    StringBuilder sb = new StringBuilder(original);\n    if(sb.length()!=0) {\n        sb.append(delimiter).append(addition);\n    } else {\n        sb.append(addition);\n    }\n    return sb.toString();\n}\n\n\n// A more generic case.\n// ... means a list of indeterminate length of Strings.\npublic String appendWithDelimitersGeneric(String delimiter, String... strings) {\n    StringBuilder sb = new StringBuilder();\n    for (String string : strings) {\n        if(sb.length()!=0) {\n            sb.append(delimiter).append(string);\n        } else {\n            sb.append(string);\n        }\n    }\n\n    return sb.toString();\n}\n\npublic void testAppendWithDelimiters() {\n    String string = appendWithDelimitersGeneric(",", "string1", "string2", "string3");\n}\n</code></pre>\n'}, {'answer_id': 63324, 'author': 'Yaba', 'author_id': 7524, 'author_profile': 'https://Stackoverflow.com/users/7524', 'pm_score': 0, 'selected': False, 'text': '<p>Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:</p>\n\n<pre><code>public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {\n        if ( original == null ) {\n                StringBuffer buffer = new StringBuffer();\n                buffer.append(addition);\n                return buffer;\n        } else {\n                buffer.append(delimiter);\n                buffer.append(addition);\n                return original;\n        }\n}\n</code></pre>\n\n<p>After you have finished creating your string simply call toString() on the returned StringBuffer.</p>\n'}, {'answer_id': 63351, 'author': 'Eric Normand', 'author_id': 7492, 'author_profile': 'https://Stackoverflow.com/users/7492', 'pm_score': 3, 'selected': False, 'text': '<p>I would use Google Collections.  There is a nice Join facility.<br>\n<a href="http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html" rel="noreferrer">http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html</a></p>\n\n<p>But if I wanted to write it on my own,</p>\n\n<pre><code>package util;\n\nimport java.util.ArrayList;\nimport java.util.Iterable;\nimport java.util.Collections;\nimport java.util.Iterator;\n\npublic class Utils {\n    // accept a collection of objects, since all objects have toString()\n    public static String join(String delimiter, Iterable&lt;? extends Object&gt; objs) {\n        if (objs.isEmpty()) {\n            return "";\n        }\n        Iterator&lt;? extends Object&gt; iter = objs.iterator();\n        StringBuilder buffer = new StringBuilder();\n        buffer.append(iter.next());\n        while (iter.hasNext()) {\n            buffer.append(delimiter).append(iter.next());\n        }\n        return buffer.toString();\n    }\n\n    // for convenience\n    public static String join(String delimiter, Object... objs) {\n        ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;();\n        Collections.addAll(list, objs);\n        return join(delimiter, list);\n    }\n}\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 63407, 'author': 'Aaron', 'author_id': 2628, 'author_profile': 'https://Stackoverflow.com/users/2628', 'pm_score': 0, 'selected': False, 'text': '<p>Instead of using string concatenation, you should use StringBuilder if your code is not threaded, and StringBuffer if it is.</p>\n'}, {'answer_id': 63418, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You\'re making this a little more complicated than it has to be. Let\'s start with the end of your example:</p>\n\n<pre><code>String parameterString = "";\nif ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );\nif ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );\n</code></pre>\n\n<p>With the small change of using a StringBuilder instead of a String, this becomes:</p>\n\n<pre><code>StringBuilder parameterString = new StringBuilder();\nif (condition) parameterString.append("elementName").append(",");\nif (anotherCondition) parameterString.append("anotherElementName").append(",");\n...\n</code></pre>\n\n<p>When you\'re done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:</p>\n\n<pre><code>if (parameterString.length() &gt; 0) \n    parameterString.deleteCharAt(parameterString.length() - 1);\n</code></pre>\n\n<p>And finally, get the string you want with</p>\n\n<pre><code>parameterString.toString();\n</code></pre>\n\n<p>You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings. </p>\n'}, {'answer_id': 63840, 'author': 'MetroidFan2002', 'author_id': 8026, 'author_profile': 'https://Stackoverflow.com/users/8026', 'pm_score': 0, 'selected': False, 'text': '<pre><code>//Note: if you have access to Java5+, \n//use StringBuilder in preference to StringBuffer.  \n//All that has to be replaced is the class name.  \n//StringBuffer will work in Java 1.4, though.\n\nappendWithDelimiter( StringBuffer buffer, String addition, \n    String delimiter ) {\n    if ( buffer.length() == 0) {\n        buffer.append(addition);\n    } else {\n        buffer.append(delimiter);\n        buffer.append(addition);\n    }\n}\n\n\nStringBuffer parameterBuffer = new StringBuffer();\nif ( condition ) { \n    appendWithDelimiter(parameterBuffer, "elementName", "," );\n}\nif ( anotherCondition ) {\n    appendWithDelimiter(parameterBuffer, "anotherElementName", "," );\n}\n\n//Finally, to return a string representation, call toString() when returning.\nreturn parameterBuffer.toString(); \n</code></pre>\n'}, {'answer_id': 76070, 'author': 'Mark B', 'author_id': 13070, 'author_profile': 'https://Stackoverflow.com/users/13070', 'pm_score': 1, 'selected': False, 'text': '<p>With Java 5 variable args, so you don\'t have to stuff all your strings into a collection or array explicitly:</p>\n\n<pre><code>import junit.framework.Assert;\nimport org.junit.Test;\n\npublic class StringUtil\n{\n    public static String join(String delim, String... strings)\n    {\n        StringBuilder builder = new StringBuilder();\n\n        if (strings != null)\n        {\n            for (String str : strings)\n            {\n                if (builder.length() &gt; 0)\n                {\n                    builder.append(delim).append(" ");\n                }\n                builder.append(str);\n            }\n        }           \n        return builder.toString();\n    }\n    @Test\n    public void joinTest()\n    {\n        Assert.assertEquals("", StringUtil.join(",", null));\n        Assert.assertEquals("", StringUtil.join(",", ""));\n        Assert.assertEquals("", StringUtil.join(",", new String[0]));\n        Assert.assertEquals("test", StringUtil.join(",", "test"));\n        Assert.assertEquals("foo, bar", StringUtil.join(",", "foo", "bar"));\n        Assert.assertEquals("foo, bar, x", StringUtil.join(",", "foo", "bar", "x"));\n    }\n}\n</code></pre>\n'}, {'answer_id': 76216, 'author': 'user13276', 'author_id': 13276, 'author_profile': 'https://Stackoverflow.com/users/13276', 'pm_score': 0, 'selected': False, 'text': "<p>So a couple of things you might do to get the feel that it seems like you're looking for:</p>\n\n<p>1) Extend List class - and add the join method to it.  The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)</p>\n\n<p>2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class:  so you could write that join method and add it as an extension method to List or even to Collection.</p>\n\n<p>Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.</p>\n\n<p>To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.</p>\n"}, {'answer_id': 297128, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 2, 'selected': False, 'text': '<p>Use StringBuilder and class <code>Separator</code></p>\n\n<pre><code>StringBuilder buf = new StringBuilder();\nSeparator sep = new Separator(", ");\nfor (String each : list) {\n    buf.append(sep).append(each);\n}\n</code></pre>\n\n<p>Separator wraps a delimiter. The delimiter is returned by Separator\'s <code>toString</code> method, unless on the first call which returns the empty string!</p>\n\n<p>Source code for class <code>Separator</code></p>\n\n<pre><code>public class Separator {\n\n    private boolean skipFirst;\n    private final String value;\n\n    public Separator() {\n        this(", ");\n    }\n\n    public Separator(String value) {\n        this.value = value;\n        this.skipFirst = true;\n    }\n\n    public void reset() {\n        skipFirst = true;\n    }\n\n    public String toString() {\n        String sep = skipFirst ? "" : value;\n        skipFirst = false;\n        return sep;\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 2179425, 'author': 'dfa', 'author_id': 89266, 'author_profile': 'https://Stackoverflow.com/users/89266', 'pm_score': 0, 'selected': False, 'text': '<p>using <a href="http://bitbucket.org/dfa/dollar" rel="nofollow noreferrer">Dollar</a> is simple as typing:</p>\n\n<pre><code>String joined = $(aCollection).join(",");\n</code></pre>\n\n<p>NB: it works also for Array and other data types</p>\n\n<h2>Implementation</h2>\n\n<p>Internally it uses a very neat trick:</p>\n\n<pre><code>@Override\npublic String join(String separator) {\n    Separator sep = new Separator(separator);\n    StringBuilder sb = new StringBuilder();\n\n    for (T item : iterable) {\n        sb.append(sep).append(item);\n    }\n\n    return sb.toString();\n}\n</code></pre>\n\n<p>the class <code>Separator</code> return the empty String only the first time that it is invoked, then it returns the separator:</p>\n\n<pre><code>class Separator {\n\n    private final String separator;\n    private boolean wasCalled;\n\n    public Separator(String separator) {\n        this.separator = separator;\n        this.wasCalled = false;\n    }\n\n    @Override\n    public String toString() {\n        if (!wasCalled) {\n            wasCalled = true;\n            return "";\n        } else {\n            return separator;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 3338199, 'author': 'java al', 'author_id': 402658, 'author_profile': 'https://Stackoverflow.com/users/402658', 'pm_score': 0, 'selected': False, 'text': '<p>Slight improvement [speed] of version from izb:</p>\n\n<pre><code>public static String join(String[] strings, char del)\n{\n    StringBuilder sb = new StringBuilder();\n    int len = strings.length;\n\n    if(len &gt; 1) \n    {\n       len -= 1;\n    }else\n    {\n       return strings[0];\n    }\n\n    for (int i = 0; i &lt; len; i++)\n    {\n       sb.append(strings[i]).append(del);\n    }\n\n    sb.append(strings[i]);\n\n    return sb.toString();\n}\n</code></pre>\n'}, {'answer_id': 6011632, 'author': 'Kevin', 'author_id': 357951, 'author_profile': 'https://Stackoverflow.com/users/357951', 'pm_score': 6, 'selected': False, 'text': '<p>In the case of Android, the StringUtils class from commons isn\'t available, so for this I used</p>\n\n<pre><code>android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)\n</code></pre>\n\n<p><a href="http://developer.android.com/reference/android/text/TextUtils.html">http://developer.android.com/reference/android/text/TextUtils.html</a></p>\n'}, {'answer_id': 12471817, 'author': 'Alex K', 'author_id': 876298, 'author_profile': 'https://Stackoverflow.com/users/876298', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://code.google.com/p/guava-libraries/">Google\'s Guava library</a> has <strong><em><a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Joiner.html">com.google.common.base.Joiner</a></em></strong> class which helps to solve such tasks.</p>\n\n<p>Samples:</p>\n\n<pre><code>"My pets are: " + Joiner.on(", ").join(Arrays.asList("rabbit", "parrot", "dog")); \n// returns "My pets are: rabbit, parrot, dog"\n\nJoiner.on(" AND ").join(Arrays.asList("field1=1" , "field2=2", "field3=3"));\n// returns "field1=1 AND field2=2 AND field3=3"\n\nJoiner.on(",").skipNulls().join(Arrays.asList("London", "Moscow", null, "New York", null, "Paris"));\n// returns "London,Moscow,New York,Paris"\n\nJoiner.on(", ").useForNull("Team held a draw").join(Arrays.asList("FC Barcelona", "FC Bayern", null, null, "Chelsea FC", "AC Milan"));\n// returns "FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan"\n</code></pre>\n\n<hr>\n\n<p>Here is an <a href="http://code.google.com/p/guava-libraries/wiki/StringsExplained">article about Guava\'s string utilities</a>.</p>\n'}, {'answer_id': 20013838, 'author': 'Craig P. Motlin', 'author_id': 23572, 'author_profile': 'https://Stackoverflow.com/users/23572', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re using <a href="https://www.eclipse.org/collections/" rel="nofollow noreferrer">Eclipse Collections</a>, you can use <code>makeString()</code> or <code>appendString()</code>.</p>\n\n<p><code>makeString()</code> returns a <code>String</code> representation, similar to <code>toString()</code>.</p>\n\n<p>It has three forms</p>\n\n<ul>\n<li><code>makeString(start, separator, end)</code></li>\n<li><code>makeString(separator)</code> defaults start and end to empty strings</li>\n<li><code>makeString()</code> defaults the separator to <code>", "</code> (comma and space)</li>\n</ul>\n\n<p>Code example:</p>\n\n<pre><code>MutableList&lt;Integer&gt; list = FastList.newListWith(1, 2, 3);\nassertEquals("[1/2/3]", list.makeString("[", "/", "]"));\nassertEquals("1/2/3", list.makeString("/"));\nassertEquals("1, 2, 3", list.makeString());\nassertEquals(list.toString(), list.makeString("[", ", ", "]"));\n</code></pre>\n\n<p><code>appendString()</code> is similar to <code>makeString()</code>, but it appends to an <code>Appendable</code> (like <code>StringBuilder</code>) and is <code>void</code>. It has the same three forms, with an additional first argument, the Appendable.</p>\n\n<pre><code>MutableList&lt;Integer&gt; list = FastList.newListWith(1, 2, 3);\nAppendable appendable = new StringBuilder();\nlist.appendString(appendable, "[", "/", "]");\nassertEquals("[1/2/3]", appendable.toString());\n</code></pre>\n\n<p>If you can\'t convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.</p>\n\n<pre><code>List&lt;Object&gt; list = ...;\nListAdapter.adapt(list).makeString(",");\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse collections.</p>\n'}, {'answer_id': 22577623, 'author': 'micha', 'author_id': 1115554, 'author_profile': 'https://Stackoverflow.com/users/1115554', 'pm_score': 5, 'selected': False, 'text': '<p>In Java 8 you can use <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-" rel="noreferrer"><code>String.join()</code></a>:</p>\n\n<pre><code>List&lt;String&gt; list = Arrays.asList("foo", "bar", "baz");\nString joined = String.join(" and ", list); // "foo and bar and baz"\n</code></pre>\n\n<p>Also have a look at <a href="https://stackoverflow.com/a/22577565/1115554">this answer</a> for a Stream API example.</p>\n'}, {'answer_id': 22659416, 'author': 'Thamme Gowda', 'author_id': 1506477, 'author_profile': 'https://Stackoverflow.com/users/1506477', 'pm_score': 2, 'selected': False, 'text': "<p>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)</p>\n\n<pre><code>/**\n *\n * @param delim : String that should be kept in between the parts\n * @param parts : parts that needs to be joined\n * @return  a String that's formed by joining the parts\n */\nprivate static final String join(String delim, String... parts) {\n    StringBuilder builder = new StringBuilder();\n    for (int i = 0; i &lt; parts.length - 1; i++) {\n        builder.append(parts[i]).append(delim);\n    }\n    if(parts.length &gt; 0){\n        builder.append(parts[parts.length - 1]);\n    }\n    return builder.toString();\n}\n</code></pre>\n"}, {'answer_id': 27599779, 'author': 'gladiator', 'author_id': 1072826, 'author_profile': 'https://Stackoverflow.com/users/1072826', 'pm_score': 5, 'selected': False, 'text': '<p>in Java 8 you can do this like:</p>\n\n<pre class="lang-java prettyprint-override"><code>list.stream().map(Object::toString)\n        .collect(Collectors.joining(delimiter));\n</code></pre>\n\n<p>if list has nulls you can use:</p>\n\n<pre class="lang-java prettyprint-override"><code>list.stream().map(String::valueOf)\n        .collect(Collectors.joining(delimiter))\n</code></pre>\n\n<p>it also supports prefix and suffix:</p>\n\n<pre class="lang-java prettyprint-override"><code>list.stream().map(String::valueOf)\n        .collect(Collectors.joining(delimiter, prefix, suffix));\n</code></pre>\n'}, {'answer_id': 28063943, 'author': 'рüффп', 'author_id': 628006, 'author_profile': 'https://Stackoverflow.com/users/628006', 'pm_score': 1, 'selected': False, 'text': '<p>For those who are in a Spring context their <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html" rel="nofollow">StringUtils</a> class is useful as well:</p>\n\n<p>There are many useful shortcuts like:</p>\n\n<ul>\n<li>collectionToCommaDelimitedString(Collection coll)</li>\n<li>collectionToDelimitedString(Collection coll, String delim)</li>\n<li>arrayToDelimitedString(Object[] arr, String delim)</li>\n</ul>\n\n<p>and many others. </p>\n\n<p>This can be helpful if you are not already using Java 8 and you are already in a Spring context.</p>\n\n<p>I prefer it against the Apache Commons (although very good as well) for the Collection support which is easier like this:</p>\n\n<pre><code>// Encoding Set&lt;String&gt; to String delimited \nString asString = org.springframework.util.StringUtils.collectionToDelimitedString(codes, ";");\n\n// Decoding String delimited to Set\nSet&lt;String&gt; collection = org.springframework.util.StringUtils.commaDelimitedListToSet(asString);\n</code></pre>\n'}, {'answer_id': 29135746, 'author': 'maXp', 'author_id': 3094065, 'author_profile': 'https://Stackoverflow.com/users/3094065', 'pm_score': 0, 'selected': False, 'text': "<p>Fix answer Rob Dickerson.</p>\n\n<p>It's easier to use:</p>\n\n<pre><code>public static String join(String delimiter, String... values)\n{\n    StringBuilder stringBuilder = new StringBuilder();\n\n    for (String value : values)\n    {\n        stringBuilder.append(value);\n        stringBuilder.append(delimiter);\n    }\n\n    String result = stringBuilder.toString();\n\n    return result.isEmpty() ? result : result.substring(0, result.length() - 1);\n}\n</code></pre>\n"}, {'answer_id': 33451093, 'author': 'gstackoverflow', 'author_id': 2674303, 'author_profile': 'https://Stackoverflow.com/users/2674303', 'pm_score': 3, 'selected': False, 'text': '<h2>Java 8</h2>\n\n<pre><code>stringCollection.stream().collect(Collectors.joining(", "));\n</code></pre>\n'}, {'answer_id': 36839833, 'author': 'Ankit Lalan', 'author_id': 6251178, 'author_profile': 'https://Stackoverflow.com/users/6251178', 'pm_score': 2, 'selected': False, 'text': '<p>If you are using Spring MVC then you can try following steps.</p>\n\n<pre><code>import org.springframework.util.StringUtils;\n\nList&lt;String&gt; groupIds = new List&lt;String&gt;;   \ngroupIds.add("a");    \ngroupIds.add("b");    \ngroupIds.add("c");\n\nString csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());\n</code></pre>\n\n<p>It will result to <code>a,b,c</code></p>\n'}, {'answer_id': 39067118, 'author': 'Philipp Grigoryev', 'author_id': 3281886, 'author_profile': 'https://Stackoverflow.com/users/3281886', 'pm_score': 0, 'selected': False, 'text': '<p>I personally quite often use  the following simple solution for logging purposes:</p>\n\n<pre><code>List lst = Arrays.asList("ab", "bc", "cd");\nString str = lst.toString().replaceAll("[\\\\[\\\\]]", "");\n</code></pre>\n'}, {'answer_id': 49860671, 'author': 'Luis Aguilar', 'author_id': 9572533, 'author_profile': 'https://Stackoverflow.com/users/9572533', 'pm_score': 3, 'selected': False, 'text': '<p>Java 8 Native Type</p>\n\n<pre><code>List&lt;Integer&gt; example;\nexample.add(1);\nexample.add(2);\nexample.add(3);\n...\nexample.stream().collect(Collectors.joining(","));\n</code></pre>\n\n<p>Java 8 Custom Object:</p>\n\n<pre><code>List&lt;Person&gt; person;\n...\nperson.stream().map(Person::getAge).collect(Collectors.joining(","));\n</code></pre>\n'}, {'answer_id': 59099866, 'author': 'Dhruv Naik', 'author_id': 10789713, 'author_profile': 'https://Stackoverflow.com/users/10789713', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to apply comma in a List of object\'s properties. This is the way i found most useful. </p>\n\n<p>here <strong>getName()</strong> is a string property of a class i have been trying to add "," to.</p>\n\n<p><strong>String message = listName.stream().map(list -> list.getName()).collect(Collectors.joining(", "));</strong></p>\n'}, {'answer_id': 73844686, 'author': 'VIVek', 'author_id': 12591119, 'author_profile': 'https://Stackoverflow.com/users/12591119', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n<p>Don't use join, delimiter or StringJoiner methods and classes as they\nwont work below Android N and O versions. Else use a simple code logic\nas;</p>\n</blockquote>\n<pre><code> List&lt;String&gt; tags= emp.getTags();\n        String tagTxt=&quot;&quot;;\n        for (String s : tags) {\n            if (tagTxt.isEmpty()){\n                tagTxt=s;\n            }else\n                tagTxt= tagTxt+&quot;, &quot;+s;\n        }  \n</code></pre>\n"}]
['https://Stackoverflow.com/questions/63150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2041950/']