Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the first iteration through a for-each loop in Java

Tags:

java

foreach

I'm working on a server that returns character separated lists to its client. In order to build these lists I have to detect the first iteration through a for-each loop:

    StringBuilder builder = new StringBuilder() ;     boolean firstIterationFlag = true ;      for ( String s : list ){         if ( firstIterationFlag) {             firstIterationFlag = false ;         } else {             builder.append(separator);         }         builder.append(s) ;             }    return builder.toString() ; 

Is there a way of doing this without the flag?

like image 834
user903724 Avatar asked May 08 '12 16:05

user903724


People also ask

Is there a way to access an iteration counter in Java for-each loop?

Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.

DO for loops check the condition first?

do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time. After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.

How do you run a foreach loop only once in Java?

There is, just put a break at the end of the block. But instead of doing this just get the one item you want out of the collection instead of "looping once". foreach traverses each element once it does not loop.

Does for-each iterate in order Java?

Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.


1 Answers

One simpler way for this situation is to note that you can always append an empty string:

// For the first iteration, use a no-op separator String currentSeparator = ""; for (String s : list) {     builder.append(currentSeparator);     builder.append(s);     // From the second iteration onwards, use this     currentSeparator = separator; } 

Alternatively (and preferrably) use Guava's Joiner class to start with :)

This "joiner" scenario is almost always the one given for this requirement - so just use Joiner. For other scenarios, either use a regular for loop or use the condition as per your code.

like image 196
Jon Skeet Avatar answered Oct 17 '22 22:10

Jon Skeet