java foreach skip first iteration

2019-03-09 15:20发布

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

12条回答
欢心
2楼-- · 2019-03-09 16:13

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

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

查看更多
劫难
3楼-- · 2019-03-09 16:14

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.

查看更多
SAY GOODBYE
4楼-- · 2019-03-09 16:15

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++;
}
查看更多
相关推荐>>
5楼-- · 2019-03-09 16:17
for (Car car : cars)
{
   if (car == cars[0]) continue;
   ...
}

Elegant enough for me.

查看更多
等我变得足够好
6楼-- · 2019-03-09 16:17

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.

查看更多
狗以群分
7楼-- · 2019-03-09 16:18

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)

查看更多
登录 后发表回答