java foreach skip first iteration

前端 未结 11 925
刺人心
刺人心 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:46

    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
    
    0 讨论(0)
  • 2021-02-01 12:47

    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++;
    }
    
    0 讨论(0)
  • 2021-02-01 12:48

    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)

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

    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++;
        }
    
    0 讨论(0)
  • 2021-02-01 12:52

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

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