Note that there are some explanatory texts on larger screens.

plurals
  1. POBest Loop Idiom for special casing the last element
    text
    copied!<p>I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (for example every normal element will be comma separated except for the last case).</p> <p>Is there some best practice idiom or elegant form that doesn't require duplicating code or shoving in an if, else in the loop.</p> <p>For example I have a list of strings that I want to print in a comma separated list. (the do while solution already assumes the list has 2 or more elements otherwise it'd be just as bad as the more correct for loop with conditional).</p> <p>e.g. List = ("dog", "cat", "bat")</p> <p>I want to print "[dog, cat, bat]"</p> <p>I present 2 methods the</p> <ol> <li><p>For loop with conditional</p> <pre><code>public static String forLoopConditional(String[] items) { String itemOutput = "["; for (int i = 0; i &lt; items.length; i++) { // Check if we're not at the last element if (i &lt; (items.length - 1)) { itemOutput += items[i] + ", "; } else { // last element itemOutput += items[i]; } } itemOutput += "]"; return itemOutput; } </code></pre></li> <li><p>do while loop priming the loop</p> <pre><code>public static String doWhileLoopPrime(String[] items) { String itemOutput = "["; int i = 0; itemOutput += items[i++]; if (i &lt; (items.length)) { do { itemOutput += ", " + items[i++]; } while (i &lt; items.length); } itemOutput += "]"; return itemOutput; } </code></pre> <p>Tester class:</p> <pre><code>public static void main(String[] args) { String[] items = { "dog", "cat", "bat" }; System.out.println(forLoopConditional(items)); System.out.println(doWhileLoopPrime(items)); } </code></pre></li> </ol> <p>In the Java AbstractCollection class it has the following implementation (a little verbose because it contains all edge case error checking, but not bad).</p> <pre><code>public String toString() { Iterator&lt;E&gt; i = iterator(); if (! i.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (! i.hasNext()) return sb.append(']').toString(); sb.append(", "); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload