79

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
   .
   .
}
3
  • 5
    For reference, Java5 hasn't been "new" for 5-6 years. Commented Apr 18, 2011 at 23:46
  • I suspect this is something the foreach loop was expressly not intended to handle. Commented Apr 18, 2011 at 23:47
  • 1
    Guess I should have said newer :P Commented Apr 18, 2011 at 23:51

11 Answers 11

87

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
Sign up to request clarification or add additional context in comments.

Comments

84

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.  

3 Comments

Don't all the ordered collection types and arrays have such a "subset" type command?
@RHSeeger No, I don't think so. I mean, the only thing that makes a List a List is the fact that it is ordered, so how could you specify the bounds of a subset of an unordered collection? I suppose you could skip the first iteration of an Iterator, but there would be no guarantee that you always skip the same first element.
There was also one more bracket :)
29
for (Car car : cars)
{
   if (car == cars[0]) continue;
   ...
}

Elegant enough for me.

3 Comments

Seems clearer this way to me ... and presumably a lot faster on a big list?
Unless one element is repeated but +1 for elegance.
Ew. Adding an unnecessary condition to each iteration of a loop? No thanks.
28

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)

Comments

19

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

1 Comment

You should be able to comment now.
7

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.

Comments

3

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

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

1 Comment

Does it assume that the cars is a List?
2

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

Comments

1

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.

Comments

1

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.