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

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).
  • Oliver

    Sweet – I really like that tip.

  • Bill

    Agreed, great tip.

  • Bruce

    Can this be done by ‘Separation of Concerns’

  • http://www.girolami.org/blog Philippe

    Totally agreed… a programmer on my team did it last week when he wrote the utility function to convert collections to such strings and vice-versa… I was pleasently surprised :)

  • Jason

    Very elegant.

  • Ivan

    I’ve used this same fellow as far back as I can remember, but I always felt dirty about:
    a) Wasted effort appending a blank string for the first iteration.
    b) Subsequent redundant assignments to the sep variable.

    Sure, I feel bad, but it’s still my hammer for every nail.

  • Joel Hockey

    Nice. I often use the following idiom as well:

    <pre>
    StringBuffer sb = new StringBuffer();
    List l = …;
    String sep = ",";
    for (Iterator i = l.iterator(); i.hasNext(); ) {
    String s = (String) i.next();
    sb.append(s).append(sep);
    }

    return out.substring(0, sb.length() – sep.length());
    </pre>
    I like it because it is a little more explicit, but without any conditional processing within a loop.

  • http://www.brunningonline.net/simon/blog/ Simon Brunning

    Nice – but don’t reinvent the wheel: http://jakarta.apache.org/commons/lang/api/org/apache/commons/lang/StringUtils.html#join(java.util.Iterator, java.lang.String)

    Hmmm, funny URL with a space in it.