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:18

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.

查看更多
Explosion°爆炸
3楼-- · 2019-03-09 16:18

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++;
    }
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-09 16:21

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
查看更多
萌系小妹纸
5楼-- · 2019-03-09 16:22

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.  

查看更多
对你真心纯属浪费
6楼-- · 2019-03-09 16:22

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

查看更多
唯我独甜
7楼-- · 2019-03-09 16:25

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();
}
查看更多
登录 后发表回答