java foreach skip first iteration

前端 未结 11 942
刺人心
刺人心 2021-02-01 12:05

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         


        
相关标签:
11条回答
  • 2021-02-01 12:27

    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.

    0 讨论(0)
  • 2021-02-01 12:34

    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.

    0 讨论(0)
  • 2021-02-01 12:40

    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();
    }
    
    0 讨论(0)
  • 2021-02-01 12:41
    for (Car car : cars)
    {
       if (car == cars[0]) continue;
       ...
    }
    

    Elegant enough for me.

    0 讨论(0)
  • 2021-02-01 12:43

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

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

    0 讨论(0)
  • 2021-02-01 12:44

    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.  

    0 讨论(0)
提交回复
热议问题