Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java foreach skip first iteration

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    .    . } 
like image 587
Amir Afghani Avatar asked Apr 18 '11 23:04

Amir Afghani


2 Answers

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 
like image 170
Kao Avatar answered Sep 20 '22 14:09

Kao


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.  

like image 21
Sean Adkinson Avatar answered Sep 22 '22 14:09

Sean Adkinson