user903724 user903724 - 9 months ago 37
Java Question

Detecting the first iteration through a for-each loop in Java

I'm working on a server that returns character separated lists to its' client.
In order to build these lists I have to detect the first iteration through a for-each loop:

StringBuilder builder = new StringBuilder() ;
boolean firstIterationFlag = true ;

for ( String s : list ){
if ( firstIterationFlag) {
firstIterationFlag = false ;
} else {
builder.append(s) ;
return builder.toString() ;

Is there a way of doing this without the flag?


One simpler way for this situation is to note that you can always append an empty string:

// For the first iteration, use a no-op separator
String currentSeparator = "";
for (String s : list) {
    // From the second iteration onwards, use this
    currentSeparator = separator;

Alternatively (and preferrably) use Guava's Joiner class to start with :)

This "joiner" scenario is almost always the one given for this requirement - so just use Joiner. For other scenarios, either use a regular for loop or use the condition as per your code.