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

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) {
    builder.append(currentSeparator);
    builder.append(s);
    // 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)