Code idiom: inserting a separator between the elements in a list
# 2003-02-18 17:06:28 -0500 | Java | 8 CommentsI 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
sepbecomes redundant after the first iteration; but the assignment is cheap (and cheaper than any conditional).
Sweet - I really like that tip.
Agreed, great tip.
Can this be done by ‘Separation of Concerns’
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 :)
Very elegant.
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.
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.
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.