gpt4 book ai didi

java - 增强 for 循环的最后一次迭代

转载 作者:行者123 更新时间:2023-11-29 04:36:41 28 4
gpt4 key购买 nike

我正在尝试使用增强的 for 循环遍历 Iterable,但我无法确定何时处理最后一个值。

     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 循环中不是解决这个问题的方法。

最佳答案

如果您想知道迭代最后一个元素的时间,请在标准的 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
}
}

关于java - 增强 for 循环的最后一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41134339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com