tags:

views:

2765

answers:

17

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.

+18  A: 

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

Dinah
the most efficient solution for this problem. +1.
Chandan .
+1  A: 

If you convert it to a classic index loop, yes.

Or you could just delete the last comma after it's done. Like so:

int[] array = {1, 2, 3...};
StringBuilder

builder = new StringBuilder();

for(int i : array)
{
    builder.append(i + ",");
}

if(builder.charAt((builder.length() - 1) == ','))
    builder.deleteCharAt(builder.length() - 1);

Me, I just use StringUtils.join() from commons-lang.

sblundy
+2  A: 

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() :-)

gareth

Gareth Davis
+2  A: 

Explicit loops always work better than implicit ones.

builder.append( "" + array[0] );
for( int i = 1; i != array.length; i += 1 ) {
   builder.append( ", " + array[i] );
}

You should wrap the whole thing in an if-statement just in case you're dealing with a zero-length array.

S.Lott
I like this approach because it does not needlessly perform a test each iteration. The only thing I would add is that builder can append integers directly so there is no need to use "" + int, just append(array[0]).
Josh
You need one more if around the whole lot to ensure that array has at least one element.
Tom Leys
why does everyone keep using examples with string concatenation INSIDE of append? the ", " + x compiles into new StringBuilder(", ").append( x ).toString()...
John Gardner
@Josh and @John: Just following the n00b example. Don't want to introduce too many things at once. Your point is very good, however.
S.Lott
@Tom: Right. I think I already said that. No edit required.
S.Lott
+71  A: 

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

Jon Skeet
Too bad I can only up-vote this once.
erickson
I like this solution. It might have a little performance cost, but in most cases it is near zero.
PhiLho
yeah, the two suggestions deserve 2 up votes!
John Gardner
Just don't add anything to the 'builder' before you append in the loop. While the code is correct, it naively assumes 'builder' is always created just for outputting the array, which as a SO snippet is okay, but in real life is hardly ever the case.
Robert Paulson
Actually it's almost always been the case in my experience of having used this pattern quite a few times. It's also incredibly obvious when it's not the case. Fortunately the slightly wordier pattern of keeping a boolean "firstIteration" variable is easy to migrate to where necessary.
Jon Skeet
Well, we all know that we shouldn't copy/paste code snippets, but I'm sure we're all guilty of it. I only bring it up because if I'm writing an array out, I'm usually writing other stuff too, and the StringBuilder is passed as a parameter to the code that writes to it. :)
Robert Paulson
Neat!For a more general solution, see my `Class Separator` answer.
Adrian
Good pattern, but builder.length() != 0 is brittle -- imagine something gets added (conditionally!) to the buffer before your loop. Instead, use an `isFirst` boolean flag. Bonus: faster too.
Jason Cohen
@Jason: I certainly use the "isFirst" pattern where the builder won't be empty on the first iteration. However, when it's not needed, it adds a fair amount of bloat to the implementation in my experience.
Jon Skeet
This is a good idea here but say you wanted to do a list of String instead and the first Strings could be empty. This could have an unintended result. ;)
Peter Lawrey
I think this is not the most efficient solution. There are 'n' number of unnecessary if checks. Dinah's solution is better. First add all comas then rollback the addition of last comma. That looks the most efficient. Consider if the array has 1000 elements!
Chandan .
@Peter: If the first string is empty, I'd imagine you'd still want a comma. Otherwise you're not representing that first empty string.
Jon Skeet
@Liverpool (etc): 1000 unnecessary checks is very, *very* unlikely to have any significant impact on performance. I might equally point out that the extra character by Dinah's solution added *might* cause the StringBuilder to have to expand, doubling the size of the final string with (cont)
Jon Skeet
unnecessary buffer space. However, the important point is readability. I happen to find my version more readable than Dinah's. If you feel the opposite way, that's fine. I'd only consider the performance impact of the unnecessary "ifs" after finding a bottleneck.
Jon Skeet
In addition, my solution is a more generally applicable one, as it only relies on being able to write. You could take my solution and change it to write to a stream etc - where you may not be able to take back the unnecessary data afterwards. I like patterns which are generally applicable.
Jon Skeet
A: 

Another approach is to have the length of the array (if available) stored in a separate variable (more efficient than re-checking the length each time). You can then compare your index to that length to determine whether or not to add the final comma.

EDIT: Another consideration is weighing the performance cost of removing a final character (which may cause a string copy) against having a conditional be checked in each iteration.

Brian
+1  A: 

Here is an solution:

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

for(int i : array)
{
    if(!firstiteration)
        builder.append(",");

    builder.append("" + i);
    firstiteration=false;
}

Look for the first iteration :)

TJMonk15
A: 

Two alternate paths here:

1: Apache Commons String Utils

2: Keep a boolean called first, set to true. In each iteration, if first is false, append your comma; after that, set first to false.

Paul Brinkley
+8  A: 

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);
      }
 }
Omar Kooheji
+10  A: 

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]);
        }
    }
bruno conde
This is a natural solution except that it depends on the array not being empty.
orcmid
@orcmid: If the array is empty, then this still gives the correct output -- an empty string. I'm not sure what your point is.
Eddie
+48  A: 

Another way to do this:

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

No if test required :-)

And since "," will be interned, no new String objects will be created within the loop.

BTW: if you don't mind the String resembling "[1, 2, 3, 4]" then you can use java.util.Arrays#toString(int[])

Arrays.toString(ints);
toolkit
Had to delete my similar answer - that'll teach me not to post before looking more carefully at other answers.
Michael Burr
Also note that this handles the potential issue Robert Paulson mentioned in another comment thread - this technique does not depend on the StringBuilder being empty when the array values are appended.
Michael Burr
Although the code is more slick/neat/fun, it is less obvious than the if version. Always use the more obvious/readable version.
Bill K
@Bill: That's not great as a hard and fast rule; there are times where the 'clever' solution is the "more correct" solution. More to the point, do you really that this version is difficult to read? Either way a maintainer would need to step through it - I don't think the difference is significant.
Greg Case
A: 

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.

Dinah
+1  A: 

You need Class Separator.

Separator s = new Separator(", ");
for(int i : array)
{
     builder.append(s).append(i);
}

The implementation of class Separator is straight forward. It wraps a string that is returned on every call of toString() except for the first call, which returns an empty string.

Adrian
+1  A: 

Based on java.util.AbstractCollection.toString(), it exits early to avoid the delimiter.

StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
for (;;) {
  buffer.append(iter.next());
  if (! iter.hasNext())
    break;
  buffer.append(delimiter);
}

It's efficient and elegant, but not as self-evident as some of the other answers.

13ren
+1  A: 

Yet another option.

StringBuilder builder = new StringBuilder();
for(int i : array)
    builder.append(',').append(i);
String text = builder.toString();
if (text.startsWith(",")) text=text.substring(1);
Peter Lawrey
I made a variation at the other question
13ren
A: 

This is almost a repeat of this StackOverflow question. What you want is StringUtils, and to call the join method.

StringUtils.join(strArr, ',');
Phil H
A: 

Many of the solutions described here are a bit over the top, IMHO, especially those that rely on external libraries. There is a nice clean, clear idiom for achieving a comma separated list that I have always used. It relies on the conditional (?) operator:

Edit: Original solution correct, but non-optimal according to comments. Trying a second time:

    int[] array = {1, 2, 3};
    StringBuilder builder = new StringBuilder();
    for (int i = 0 ;  i < array.length; i++)
           builder.append(i == 0 ? "" : ",").append(array[i]);

There you go, in 4 lines of code including the declaration of the array and the StringBuilder.

Julien Chastang
But you're creating a new StringBuilder on every iteration (thanks to the + operator).
Michael Myers
Yes, if you look in the bytecode, you are right. I can't believe such a simple question can get so complicated. I wonder if the compiler can optimize here.
Julien Chastang
Provided 2nd, hopefully better solution.
Julien Chastang