Is there a way to determine if the loop is iterating for the last time. My code looks something like this:
int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();
for(int i : array)
{
builder.append("" + i);
if(!lastiteration)
builder.append(",");
}
Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.
If you convert it to a classic index loop, yes.
Or you could just delete the last comma after it's done. Like so:
Me, I just use
StringUtils.join()
from commons-lang.Based on java.util.AbstractCollection.toString(), it exits early to avoid the delimiter.
It's efficient and elegant, but not as self-evident as some of the other answers.
Another solution (perhaps the most efficient)