java foreach 跳过第一次迭代
有没有一种优雅的方法来跳过 Java5 foreach 循环中的第一次迭代?
伪代码示例:
for ( Car car : cars ) {
//skip if first, do work for rest
.
.
}
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
.
.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
使用新的 Java 8 Stream API 它实际上变得非常优雅。只需使用
skip()
方法:With new Java 8 Stream API it actually becomes very elegant. Just use
skip()
method:我不会称其为优雅,但也许比使用“第一个”布尔值更好:
除此之外,可能没有优雅的方法。
I wouldn't call it elegant, but perhaps better than using a "first" boolean:
Other than that, probably no elegant method.
对我来说足够优雅。
Elegant enough for me.
使用 Guava
Iterables.skip()
。类似的东西:(
从 msandiford 的答案 的末尾得到这个,并希望将其作为一个独立的答案)
Use Guava
Iterables.skip()
.Something like:
(Got this from the end of msandiford's answer and wanted to make it a standalone answer)
SeanA的代码有一个小错误:子列表的第二个参数被视为独占索引,所以我们可以直接写
(我似乎无法评论答案,因此是新的答案。我需要一定的声誉才能这样做吗?)
SeanA's code has a tiny error: the second argument to sublist is treated as an exclusive index, so we can just write
(I don't seem to be able to comment on answers, hence the new answer. Do I need a certain reputation to do that?)
我来得有点晚了,但是你可以使用辅助方法,例如:
并使用它,如下所示:
概括跳过“n”作为读者的练习:)
编辑 :仔细检查后,我发现 Guava 有一个
Iterables.skip(...)
此处。I came a bit late to this, but you could use a helper method, something like:
And use it something like this:
Generalizing to skip "n" is left as an exercise for the reader :)
EDIT: On closer inspection, I see that Guava has an
Iterables.skip(...)
here.我不是java人,但你可以使用:
for (Car car: cars.tail())
from java.util via Groovy JDKI'm not a java person but can you use :
for ( Car car : cars.tail() )
from java.util via Groovy JDK不太优雅,但可以与迭代器一起使用
Not so elegant but work with iterators
优雅的?并不真地。您需要检查/设置一个布尔值。
for-each 循环是出于所有实际目的使用迭代器的奇特语法。您最好只使用迭代器并在开始循环之前前进。
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.
这可能不太优雅,但可以在 for 循环之外初始化一个整数变量,并在循环内的每次迭代中递增它。
仅当计数器大于 0 时,您的程序才会执行。
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.
您可以使用计数器。尽管编码不那么成熟,但我仍然发现它是跳过列表中第一个元素的最简单方法。
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.