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
With new Java 8 Stream API it actually becomes very elegant. Just use skip()
method:
cars.stream().skip(1) // and then operations on remaining cars
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.
int counter = 0;
for ( Car car : cars ) {
//skip if first, do work for rest
if(counter>0){
//do something
}
counter++;
}
Use Guava Iterables.skip().
Something like:
for ( Car car : Iterables.skip(cars, 1) ) {
// 1st element will be skipped
}
(Got this from the end of msandiford's answer and wanted to make it a standalone answer)
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.
int ctr=0;
for(Resource child:children) {
if(ctr>0) { //this will skip the first element, i.e. when ctr=0
//do your thing from the 2nd element onwards
}
ctr++;
}
SeanA's code has a tiny error: the second argument to sublist is treated as an exclusive index, so we can just write
for (Car car : cars.subList(1, cars.size()) {
...
}
(I don't seem to be able to comment on answers, hence the new answer. Do I need a certain reputation to do that?)