# Remove-Last-Comma-Problem

is there a more elegant way to solve this problem?

List<String> paramList = new ArrayList<String>( );

StringBuilder result = new StringBuilder();
for ( String p : paramList )
{
result.append( p ).append( ", " );
}

String withoutLastComma = result.substring( 0, result.length( ) - ", ".length( ) );
System.err.println( withoutLastComma );

-
How about instead of adding comma and then removing it just not add comma to the last item? using the index based approach would have been fine. for (int i = 0; i < paramList.size()-1; i++) { result.append( p ).append( ", " ); } –  Arjang May 19 '11 at 20:01

One may use string utility methods such as StringUtil.join to concatenate elements in an array or a collection object. Consult the StringUtil API's StringUtil.join entry.

For example:

StringUtils.join(["a", "b", "c"], "--")  // => "a--b--c"

-
I will add a tool library. First i have to check the differences between apache commons and google guave. –  Jonas Apr 19 '11 at 11:23
I don't see how something this simple can justify adding a library. –  Athas Apr 24 '11 at 23:04
@Wes: If you are working with critical production code and do not want to take on unnecessary dependencies (or have a policy requirement not to use external libraries) and have the time to write/test/debug/optimize your own methods, then by all means, roll your own. I made the assumption that OP is looking for a simple solution for a non-critical task. –  Adeel Zafar Soomro Apr 25 '11 at 13:04
for ( String p : paramList )
{
if (result.length() > 0) result.append( ", " );
result.append( p );
}

-
Thanks, nice solution :-) –  Jonas Apr 19 '11 at 11:17
I've always used this method. It's clear. It looks nearly the same in any language. I've never seen where the extra comparison would ever have enough weight per iteration to make a difference. –  hometoast Apr 19 '11 at 12:44
I used this solution in .NET, until I discovered that string has a static Join method. I'm surprised Java doesn't have something similar built-in. –  Kyralessa May 20 '11 at 3:40
I like how this answer actually shows how to solve the problem, not just avoid it by using a library method. Not that using the library method is wrong though, its just you still don't see how it is actually solved. –  Andrew Hagner Mar 20 '13 at 17:45

One of possible ways is a using Joiner from Google Guava library:

result = Joiner.on(", ").join(paramList);

-

I believe it's better to know how to write it and then use a library. I usually prefer to make a check before the loop, thus avoiding to have to check every time in the loop:

int size = paramList.size();
if (size > 0) {
result.append(paramList.get(0));
for (int i = 1; i < size; ++i) {
result.append(", ").append(paramList.get(i));
}
}

-
Put the for loop inside the "then" part ... –  Stephen C Apr 19 '11 at 13:50
Done. Thanks @Stephen. –  Hosam Aly Apr 19 '11 at 17:21
+1 -- this is the best possible solution that does not call String.Join. –  Billy ONeal Apr 19 '11 at 21:35

A couple of alternate options here - any of such can simply only resolve to making the intentions clear, although it's hardly an issue.

It might be a little clearer, albeit not much, using lastIndexOf:

String withoutLastComma = result.substring(0, result.lastIndexOf(","));


Or just refactor a little, which could be more explanatory:

StringBuilder result = new StringBuilder();
for (int i = 0; i < paramList.size(); i++)
{
result.append(paramList.get(i));
if (i + 1 != paramList.size())
result.append(", ");
}
System.err.println(result);


Or, lastly, use a string utility library as linked in other answers provided; though, the thought of doing so brings the term 'sledgehammer to crack a nut' to mind, but it might well be justified depending on what other operations you require to carry out.

-
This makes the code more complex. Replacing the foreach with a for statement makes it a bit more complex. However your solution works and is correct, but you have to make sure not bringing in extra complexity. –  Gertjan Apr 19 '11 at 12:23
I would argue that complexity in such a trivial construct is far, far from being reached (though understand where you're coming from in terms of 'more complex') - it is clear and self-explanatory for the everyday / professional programmer (IMO). Even just the following of the original warrants such changes, I think: ( 0, result.length( ) - ", ".length( ) ); And, thanks for the input. :) –  Grant Thomas Apr 19 '11 at 12:27
for this sample you are right. But imagine a scenario with a couple of nested loops. In that case you get something like result[i].result[j].result[k]. In those cases a foreach might be a more readable solution because it is easy to make a small mistake like using 1 instead of i or mixup the i,j & k variable. –  Gertjan Apr 20 '11 at 8:08
@Gertjan: I agree, luckily we're not in that situation here. ;) –  Grant Thomas Apr 20 '11 at 8:36

What I use is

List<String> paramList = new ArrayList<String>( );

String separator = "";

StringBuilder result = new StringBuilder();
for (String p : paramList)
{
result.append(separator)
result.append(p);
separator = ", ";
}

System.err.println(result.toString());

-
I often use this for languages without "join" functions, like PL/SQL... –  AsKaiser Dec 4 '13 at 15:16

That's strange that nobody has mentioned iterator-wise approach so far.

So here it goes:

public static <E> String join(Iterable<E> iterable, String delim) {
Iterator<E> iterator = iterable.iterator();
if (!iterator.hasNext()) {
return "";
}

StringBuilder builder = new StringBuilder(iterator.next().toString());
while (iterator.hasNext()) {
builder.append(delim).append(iterator.next().toString());
}

return builder.toString();
}


No messing with indexes, substringing, etc, etc.

And let's use it:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
System.out.println(join(list, ", "));

-

Less intuitive but a bit neater

for (String p : paramList) {
result.append(" ,").append(p);
}

System.err.println(result.substring(2));

-
String listString = Arrays.toString(paramList.toArray());
System.err.println( listString );


Will return:

[param1, param2]


This has the added benefit of using the String.valueOf(object) method which will print 'null' in the case of null objects. The Arrays.toString() method is also pretty straight forward if you just want to reimplement it. Removing the brackets:

    int iMax = paramList.size() - 1;
if (iMax == -1) {
return "";
}
String[] params = paramList.toArray();
StringBuilder b = new StringBuilder();
for (int i = 0; ; i++) {
String param = params[i];
b.append(param);
if (i == iMax) {
return b.toString();
}
b.append(", ");
}

-

The following approach is general - it does not assume that you can look back at the results or check how many items are remaining.

List<String> paramList = new ArrayList<String>( );

String[] prefixes = {"", ", "};
int prIndex = 0;
StringBuilder result = new StringBuilder();
for (String p : paramList)
{
result.append(prefixes[prIndex]).append(p);
prIndex = 1; // Overwriting this is very cheap.
}

System.err.println(result.toString());

-

I know this pattern from SQL. You might have WHERE-Conditions or not, and if you have, the second starts with "AND", not ",". Pseudocode:

sSql = " ...." +
" FROM foo, bar, baz " +
" WHERE 1 = 1 "
if (x) sSql.append (" AND x = ?")
if (y) sSql.append (" AND y LIKE ?")
if (z) sSql.append (" AND z ")


and in a similar way, you can use a dummy column in SQL, to add dynamically every additional column with a starting ", " (pseudocode again, rb := think: radio button):

sSql = "SELECT 'dummy' ";
if (rbName) sSql += ", name ";
if (rbCity) sSql += ", city ";
if (rbZip)  sSql += ", zip ";


Of course, you can't always use a dummy, but sometimes you can.

-