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?
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 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.
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.
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.
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.
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