简体   繁体   中英

Last iteration for enhanced for loop

I am trying to loop over an Iterable using the enhanced for loop but I am not able to determine when is the last value being processed.

     public void apply(Tuple key, 
                    GlobalWindow w, 
                    Iterable<Tuple5<String, Long, List<Lane>, Long, Long>> itrbl, 
                    Collector<Tuple5<String, Long, List<Lane>, Long, Long>> clctr) throws Exception {
       long cachedUmlaufSekunde = 0;
       long currentUmlaufSekunde = 0;
       long maxUmlaufSekunde = 0;
       for(Tuple5 tuple:itrbl) {
          maxUmlaufSekunde = (long)tuple.getField(4);
          currentUmlaufSekunde = ((long)tuple.getField(1)/10)*10;
          if(currentUmlaufSekunde == (cachedUmlaufSekunde + 10)) {
            cachedUmlaufSekunde =  currentUmlaufSekunde;
          } else {
              cachedUmlaufSekunde = cachedUmlaufSekunde + 10;
          }
       }

Many questions related to this topic suggest using the function iterator.hasNext() to determine the last element but I guess using something like

    itrbl.iterator.hasNext();

within the for loop is not a solution for this.

If you want to know when the last element is being iterated over, then use the iterator form in a standard for loop instead. The enhanced- for will run through all elements of an iterable, and it's not possible to discern when the end is.

for(Iterator<Tuple5> tuplIter = iterbl.iterator(); tuplIter.hasNext(); ) {
    Tuple5 tupl = tuplIter.next();

    // check for next
    if(!tuplIter.hasNext()) {
        // logic for processing the last tuple
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM