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.
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.)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.)Here's a SSCCE benchmark I ran (related to what I had to implement) with these results:
On my example at least, skipping the check at every iteration isn't noticeably faster especially for sane volumes of data, but it is faster.
You need Class Separator.
The implementation of class
Separator
is straight forward. It wraps a string that is returned on every call oftoString()
except for the first call, which returns an empty string.This is almost a repeat of this StackOverflow question. What you want is StringUtils, and to call the join method.
If you're only turning an array into a comma delimited array, many languages have a join function for exactly this. It turns an array into a string with a delimiter between each element.
Another way to do this:
Update: For Java 8, you now have Collectors