-->

java foreach skip first iteration

2019-03-09 15:30发布

问题:

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
   .
   .
}

回答1:

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.  



回答2:

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


回答3:

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)



回答4:

for (Car car : cars)
{
   if (car == cars[0]) continue;
   ...
}

Elegant enough for me.



回答5:

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?)  



回答6:

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.



回答7:

I'm not a java person but can you use :

for ( Car car : cars.tail() ) from java.util via Groovy JDK



回答8:

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.



回答9:

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();
}


回答10:

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++;
}


回答11:

I saw some good solutions here, but for my opinion you should avoid from this:

for (Car car : cars)
{
  if (car == cars[0]) continue;
  ...   
}
  • 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.



回答12:

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++;
    }