Last iteration of enhanced for loop in java
Asked Answered
P

22

147

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.

Pola answered 12/11, 2008 at 21:56 Comment(3)
Yeah! It is funny, I just wanted to ask the exact same question!Frostbitten
The same kind of question returns (and will so). Now why would you want to create a loop if one element needs a different treatment? #157150Quadrifid
Since you have a fixed array why use the enhanced for? for(int i = 0; i< array.length; i++ if(i < array.lenth),,,Bield
B
225

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

Bernabernadene answered 12/11, 2008 at 22:6 Comment(13)
I like this solution. It might have a little performance cost, but in most cases it is near zero.Frostbitten
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.Banket
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.Bernabernadene
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. :)Banket
Neat! For a more general solution, see my Class Separator answer.Sammiesammons
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.Ileenileitis
@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.Bernabernadene
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. ;)Mandatory
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!Tigges
@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.Bernabernadene
@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)Bernabernadene
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.Bernabernadene
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.Bernabernadene
A
148

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

Auriculate answered 12/11, 2008 at 22:30 Comment(5)
Had to delete my similar answer - that'll teach me not to post before looking more carefully at other answers.Umlaut
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.Umlaut
Although the code is more slick/neat/fun, it is less obvious than the if version. Always use the more obvious/readable version.Bronchial
@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.Kei
This works although you write to other resource like filesystem's write calls. Good idea.Mcsweeney
I
39

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

Ivey answered 12/11, 2008 at 22:1 Comment(4)
the most efficient solution for this problem. +1.Tigges
Maybe it's me, but I really don't like the fact that you are removing something you just added...Pelagic
Fortega: I don't like checking every time for something that I'll do 99% of the times. It seems more logical (and it IS faster) to apply Dinah's or sblundy's solution.Laky
Most elegant solution in my opinion. Thank you!Troll
Y
33

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);
      }
 }
Yepez answered 12/11, 2008 at 22:13 Comment(0)
H
16

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

StringUtils.join(strArr, ',');
Herdsman answered 21/3, 2009 at 12:35 Comment(0)
S
14

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]);
        }
    }
Stortz answered 12/11, 2008 at 22:20 Comment(2)
This is a natural solution except that it depends on the array not being empty.Carola
@orcmid: If the array is empty, then this still gives the correct output -- an empty string. I'm not sure what your point is.Abeokuta
S
7

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

Sitnik answered 12/11, 2008 at 22:4 Comment(0)
V
6

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.

Valeryvalerye answered 12/11, 2008 at 22:5 Comment(5)
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]).Formless
You need one more if around the whole lot to ensure that array has at least one element.Klos
why does everyone keep using examples with string concatenation INSIDE of append? the ", " + x compiles into new StringBuilder(", ").append( x ).toString()...Trousers
@Formless and @John: Just following the n00b example. Don't want to introduce too many things at once. Your point is very good, however.Valeryvalerye
@Tom: Right. I think I already said that. No edit required.Valeryvalerye
A
5

As toolkit mentioned, in Java 8 we now have Collectors. Here's what the code would look like:

String joined = array.stream().map(Object::toString).collect(Collectors.joining(", "));

I think that does exactly what you're looking for, and it's a pattern you could use for many other things.

Abuzz answered 11/11, 2016 at 1:24 Comment(0)
Q
4

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.

Quinquefid answered 12/11, 2008 at 22:3 Comment(0)
T
3

Here is a 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 :)  

Tantra answered 12/11, 2008 at 22:6 Comment(0)
S
3

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.

Sammiesammons answered 14/11, 2008 at 10:0 Comment(0)
D
3

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.

Deferred answered 21/3, 2009 at 12:13 Comment(1)
You forgot to include the early return when (! i.hasNext()), which is an important part of the robustness of the overall approach. (The other solutions here handle empty collections gracefully, so yours should too! :)Seismoscope
M
1

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);
Mandatory answered 21/3, 2009 at 12:25 Comment(1)
I made a variation at the other questionDeferred
H
1

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.

Hanway answered 21/3, 2009 at 19:23 Comment(3)
But you're creating a new StringBuilder on every iteration (thanks to the + operator).Homochromous
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.Hanway
Provided 2nd, hopefully better solution.Hanway
L
1

Here's a SSCCE benchmark I ran (related to what I had to implement) with these results:

elapsed time with checks at every iteration: 12055(ms)
elapsed time with deletion at the end: 11977(ms)

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.

import java.util.ArrayList;
import java.util.List;


public class TestCommas {

  public static String GetUrlsIn(int aProjectID, List<String> aUrls, boolean aPreferChecks)
  {

    if (aPreferChecks) {

      StringBuffer sql = new StringBuffer("select * from mytable_" + aProjectID + " WHERE hash IN ");

      StringBuffer inHashes = new StringBuffer("(");
      StringBuffer inURLs = new StringBuffer("(");

      if (aUrls.size() > 0)
      {

      for (String url : aUrls)
      {

        if (inHashes.length() > 0) {
        inHashes.append(",");
        inURLs.append(",");
        }

        inHashes.append(url.hashCode());

        inURLs.append("\"").append(url.replace("\"", "\\\"")).append("\"");//.append(",");

      }

      }

      inHashes.append(")");
      inURLs.append(")");

      return sql.append(inHashes).append(" AND url IN ").append(inURLs).toString();
    }

    else {

      StringBuffer sql = new StringBuffer("select * from mytable" + aProjectID + " WHERE hash IN ");

      StringBuffer inHashes = new StringBuffer("(");
      StringBuffer inURLs = new StringBuffer("(");

      if (aUrls.size() > 0)
      {

      for (String url : aUrls)
      {
        inHashes.append(url.hashCode()).append(","); 

        inURLs.append("\"").append(url.replace("\"", "\\\"")).append("\"").append(",");
      }

      }

      inHashes.deleteCharAt(inHashes.length()-1);
      inURLs.deleteCharAt(inURLs.length()-1);

      inHashes.append(")");
      inURLs.append(")");

      return sql.append(inHashes).append(" AND url IN ").append(inURLs).toString();
    }

  }

  public static void main(String[] args) { 
        List<String> urls = new ArrayList<String>();

    for (int i = 0; i < 10000; i++) {
      urls.add("http://www.google.com/" + System.currentTimeMillis());
      urls.add("http://www.yahoo.com/" + System.currentTimeMillis());
      urls.add("http://www.bing.com/" + System.currentTimeMillis());
    }


    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 300; i++) {
      GetUrlsIn(5, urls, true);
    }
    long endTime = System.currentTimeMillis();
    System.out.println("elapsed time with checks at every iteration: " + (endTime-startTime) + "(ms)");

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 300; i++) {
      GetUrlsIn(5, urls, false);
    }
    endTime = System.currentTimeMillis();
    System.out.println("elapsed time with deletion at the end: " + (endTime-startTime) + "(ms)");
  }
}
Laky answered 1/8, 2014 at 14:58 Comment(1)
Please don't roll your own benchmarks and use OpenJDKs own micro benchmarking harness (jmh). It will warm up your code and avoid the most problematic pitfalls.Tory
C
0

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.

Canaletto answered 12/11, 2008 at 22:6 Comment(1)
Removing a final character shouldn't cause a string copy to be made. StringBuffer's delete/deleteCharAt methods eventually call the following method inside the System class identical source and destination arrays: System -> public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);Laky
H
0

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.

Hydnocarpate answered 12/11, 2008 at 22:8 Comment(1)
1) The link is dead 2) It took me longer to read the description rather than the code :)Laky
I
0

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.

Ivey answered 12/11, 2008 at 22:44 Comment(0)
M
0

In this case there is really no need to know if it is the last repetition. There are many ways we can solve this. One way would be:

String del = null;
for(int i : array)
{
    if (del != null)
       builder.append(del);
    else
       del = ",";
    builder.append(i);
}
Matelote answered 24/5, 2011 at 6:58 Comment(0)
B
0

Since its a fixed array, it would be easier simply to avoid the enhanced for... If the Object is a collection an iterator would be easier.

int nums[] = getNumbersArray();
StringBuilder builder = new StringBuilder();

// non enhanced version
for(int i = 0; i < nums.length; i++){
   builder.append(nums[i]);
   if(i < nums.length - 1){
       builder.append(",");
   }   
}

//using iterator
Iterator<int> numIter = Arrays.asList(nums).iterator();

while(numIter.hasNext()){
   int num = numIter.next();
   builder.append(num);
   if(numIter.hasNext()){
      builder.append(",");
   }
}
Bield answered 15/6, 2017 at 2:55 Comment(0)
R
0

You can use StringJoiner.

int[] array = { 1, 2, 3 };
StringJoiner stringJoiner = new StringJoiner(",");

for (int i : array) {
    stringJoiner.add(String.valueOf(i));
}

System.out.println(stringJoiner);
Race answered 10/11, 2021 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.