Last iteration of enhanced for loop in java

Another alternative is to append the comma before you append i, just not on the first iteration. (Please don’t use "" + i, by the way – you don’t really want concatenation here, and StringBuilder has a perfectly good append(int) overload.)

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for (int i : array) {
    if (builder.length() != 0) {
        builder.append(",");
    }
    builder.append(i);
}

The nice thing about this is that it will work with any Iterable – you can’t always index things. (The “add the comma and then remove it at the end” is a nice suggestion when you’re really using StringBuilder – but it doesn’t work for things like writing to streams. It’s possibly the best approach for this exact problem though.)

Leave a Comment

deneme bonusu veren sitelerbahis casino