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 w
Elegant? Not really. You'd need to check/set a boolean.
The for-each loop is for all practical purposes fancy syntax for using an iterator. You're better off just using an iterator and advancing before you start your loop.
I came a bit late to this, but you could use a helper method, something like:
public static <T> Iterable<T> skipFirst(final Iterable<T> c) {
return new Iterable<T>() {
@Override public Iterator<T> iterator() {
Iterator<T> i = c.iterator();
i.next();
return i;
}
};
}
And use it something like this:
public static void main(String[] args) {
Collection<Integer> c = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
for (Integer n : skipFirst(c)) {
System.out.println(n);
}
}
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.
Not so elegant but work with iterators
Iterator<XXXXX> rows = array.iterator();
if (rows.hasNext()){
rows.next();
}
for (; rows.hasNext();) {
XXXXX row = (XXXXX) rows.next();
}
for (Car car : cars)
{
if (car == cars[0]) continue;
...
}
Elegant enough for me.
I'm not a java person but can you use :
for ( Car car : cars.tail() )
from java.util via Groovy JDK
I wouldn't call it elegant, but perhaps better than using a "first" boolean:
for ( Car car : cars.subList( 1, cars.size() ) )
{
.
.
}
Other than that, probably no elegant method.