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

# 2003-02-18 17:06:28 -0500 | Java | 8 Comments

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

8 Responses to this entry:

  1. Oliver Says:

    Sweet - I really like that tip.

  2. Bill Says:

    Agreed, great tip.

  3. Bruce Says:

    Can this be done by ‘Separation of Concerns’

  4. Philippe Says:

    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 :)

  5. Jason Says:

    Very elegant.

  6. Ivan Says:

    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.

  7. Joel Hockey Says:

    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.

  8. Simon Brunning Says:

    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.

Leave a Reply

Click here to leave a reply