In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
For a low number of iterations (100-1000), the enhanced for loop seems to be much faster with and without JIT. On the contrary with a high number of iterations (100000000), the traditional loop is much faster.
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
Maybe you are using the wrong tool for the Job.
This is more manual than what you are doing but it's in a way more elegant if not a bit "old school"
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
This is almost a repeat of this StackOverflow question. What you want is StringUtils, and to call the join method.
StringUtils.join(strArr, ',');
Another solution (perhaps the most efficient)
int[] array = {1, 2, 3};
StringBuilder builder = new StringBuilder();
if (array.length != 0) {
builder.append(array[0]);
for (int i = 1; i < array.length; i++ )
{
builder.append(",");
builder.append(array[i]);
}
}
keep it simple and use a standard for loop:
for(int i = 0 ; i < array.length ; i ++ ){
builder.append(array[i]);
if( i != array.length - 1 ){
builder.append(',');
}
}
or just use apache commons-lang StringUtils.join()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With