2016-12-14 221 views
0

我使用增強的for循環試圖遍歷一個可迭代,但我不能確定何時是正在處理的最後一個值。末迭代增強的for循環

此主題相關
 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; 
      } 
     } 

許多問題,建議使用功能iterator.hasNext(),以確定最後的元素,但我想使用類似

itrbl.iterator.hasNext(); 

中的for循環是不是一個解決方案爲了這。

回答

2

如果您想知道何時迭代最後一個元素,請改用標準for循環中的iterator表單。增強的for將貫穿全部元素的迭代,並且不可能辨別何時結束。

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

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