Last iteration of enhanced for loop in java

2019-01-04 05:25发布

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.

21条回答
▲ chillily
2楼-- · 2019-01-04 06:09

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.

查看更多
时光不老,我们不散
3楼-- · 2019-01-04 06:09

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.

查看更多
SAY GOODBYE
4楼-- · 2019-01-04 06:11

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]);
        }
    }
查看更多
登录 后发表回答