madbean

Code idiom: inserting a separator between the elements in a list

18 Feb 2003

I use the following code idiom all the time. I know it seems simple, and I know there are other ways of doing it, but when I first saw it a penny dropped.

Writer out = ...;
List l = ...;
String sep = "";
for (Iterator i = l.iterator(); i.hasNext(); ) {
    String s = (String) i.next();
    out.write(sep);
    out.write(s);
    sep = ",";
}

You can see how this works:

  • output the separator before outputting the value,
  • the separator is blank to start with, and
  • the "real" separator is setup at the end of the first iteration.

I like it:

  • there are no explicit "is this the first/last iteration" conditionals,
  • the assignment to sep becomes redundant after the first iteration; but the assignment is cheap (and cheaper than any conditional).
  • Home
  • Blog