Is there an elegant way to skip the first iteration in a Java5 foreach loop ?
Example pseudo-code:
for ( Car car : cars ) {
//skip if first, do work for rest
.
.
}
Is there an elegant way to skip the first iteration in a Java5 foreach loop ?
Example pseudo-code:
for ( Car car : cars ) {
//skip if first, do work for rest
.
.
}
I'm not a java person but can you use :
for ( Car car : cars.tail() )
from java.util via Groovy JDKI came a bit late to this, but you could use a helper method, something like:
And use it something like this:
Generalizing to skip "n" is left as an exercise for the reader :)
EDIT: On closer inspection, I see that Guava has an
Iterables.skip(...)
here.This might not be elegant, but one could initialize an integer variable outside the for loop and increment it with every iteration within the loop. Your program would only execute if the counter is bigger than 0.
Elegant enough for me.
I saw some good solutions here, but for my opinion you should avoid from this:
The reason is that you asked to skip just on the first iteration of the loop, and this way will work only if the car which located in the first index in your container appear in it only once,
But what if this car appear more than once in the container? in that case, you will skip it again, and you will skip more iterations except the first one.
Use Guava
Iterables.skip()
.Something like:
(Got this from the end of msandiford's answer and wanted to make it a standalone answer)