Last iteration of enhanced for loop in java Last iteration of enhanced for loop in java java java

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.)


Another way to do this:

String delim = "";for (int i : ints) {    sb.append(delim).append(i);    delim = ",";}

Update: For Java 8, you now have Collectors


It might be easier to always append. And then, when you're done with your loop, just remove the final character. Tons less conditionals that way too.

You can use StringBuilder's deleteCharAt(int index) with index being length() - 1