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
.
.
}
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.
You can use a counter. Though not so mature coding, still I find it the easiest way to skip the first element from a list.
With new Java 8 Stream API it actually becomes very elegant. Just use
skip()
method:I wouldn't call it elegant, but perhaps better than using a "first" boolean:
Other than that, probably no elegant method.
SeanA's code has a tiny error: the second argument to sublist is treated as an exclusive index, so we can just write
(I don't seem to be able to comment on answers, hence the new answer. Do I need a certain reputation to do that?)
Not so elegant but work with iterators