java foreach skip first iteration

JavaForeachIterationSkip

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.  

Solution 2 - Java

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

Solution 3 - Java

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

Elegant enough for me.

Solution 4 - Java

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)

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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

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

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmir AfghaniView Question on Stackoverflow
Solution 1 - JavaSean AdkinsonView Answer on Stackoverflow
Solution 2 - JavaKaoView Answer on Stackoverflow
Solution 3 - JavaelekwentView Answer on Stackoverflow
Solution 4 - Javayop83View Answer on Stackoverflow
Solution 5 - JavaDaniel LubarovView Answer on Stackoverflow
Solution 6 - JavaclstrfsckView Answer on Stackoverflow
Solution 7 - JavaPreet SanghaView Answer on Stackoverflow
Solution 8 - JavaAngelView Answer on Stackoverflow
Solution 9 - JavaBrian RoachView Answer on Stackoverflow
Solution 10 - JavaBenjaminView Answer on Stackoverflow
Solution 11 - JavaSonakshi SharmaView Answer on Stackoverflow