Stupid Java Trick: Rethinking how to handle creating the comma-separated list

Everyone knows the simple problem of outputting a comma-separated list.  It’s an easy problem to solve and it’s normally done like this:

int[] ints = {1, 2, 3, 4, ...};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ints.length; i++) {
   sb.append(ints[i]);
   if (i+1 != ints.length) {
     sb.append(",");
   }
 }
System.out.println(sb.toString());

 

And the code will return the following output:

1,2,3,4,....

 

Which is all well and good, however, you normally don’t deal with simple arrays or Lists most of the time, you have to deal with Iterable or you’re using Java’s enhanced for loop.  Neither of these has a way to easily notify the programmer that you’re at the last item in the Iterable.  So how do you take care of this?  Simple, insert the comma before outputting the value.

int[] ints = {1, 2, 3, 4, ...};
StringBuilder sb = new StringBuilder();
for (int i : ints) {
  if (sb.length() != 0) { 
    sb.append(",");
  }
  sb.append(i);
}
System.out.println(sb.toString());

 

And the code returns the exact same output as above.

Nifty little change and you can use with any class that implements the Iterable interface.

Leave a Reply

Your email address will not be published. Required fields are marked *