Rectangle 27 0

pretty print Clearest way to comma delimit a list (Java)?


for (Item i : list)
  sb.append(',').append(i);
if (sb.charAt(0)==',') sb.deleteCharAt(0);

This is very short, very clear, but gives my sensibilities the creeping horrors. It's also a bit awkward to adapt to different delimiters, especially if a String (not char).

Note
Rectangle 27 0

pretty print Clearest way to comma delimit a list (Java)?


"Given a loop and an if, what do you think is the clearest way to have these together?"

So the question really is:

You can also unconditionally add the delimiter string, and after the loop remove the extra delimiter at the end. Then an "if list is empty then return this string" at the beginning will allow you to avoid the check at the end (as you cannot remove characters from an empty list)

Note
Rectangle 27 0

pretty print Clearest way to comma delimit a list (Java)?


if (array.length>0)          // edited in response Joachim's comment
  sb.append(array[i]);
for (int i=1; i<array.length; i++)
  sb.append(",").append(array[i]);

@Joachim thanks, you're right of course. What an ugly solution I wrote! I'll change for (int i=0; i<1; i++) to if (array.length>0).

Note