考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
当前回答
forEach的替代方案,以避免“for each”:
List<String> someList = new ArrayList<String>();
变体1(普通):
someList.stream().forEach(listItem -> {
System.out.println(listItem);
});
变体2(并行执行(更快)):
someList.parallelStream().forEach(listItem -> {
System.out.println(listItem);
});
其他回答
public static Boolean Add_Tag(int totalsize)
{
List<String> fullst = new ArrayList<String>();
for(int k=0; k<totalsize; k++)
{
fullst.addAll();
}
}
for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) {
String item = itr.next();
System.out.println(item);
}
维基百科中提到的foreach循环的概念如下:
然而,与其他for循环构造不同,foreach循环通常保持没有明确的反击:他们基本上说“这样做而不是“做x次”。这样可以避免潜在的一个错误,使代码更容易阅读。
因此,foreach循环的概念描述了该循环不使用任何显式计数器,这意味着不需要使用索引在列表中遍历,因此它将用户从一个错误中解脱出来。为了描述这一错误的一般概念,让我们举一个使用索引在列表中遍历的循环的例子。
// In this loop it is assumed that the list starts with index 0
for(int i=0; i<list.length; i++){
}
但是假设列表以索引1开始,那么这个循环将抛出一个异常,因为它将在索引0处找不到元素,这个错误被称为off-by-one错误。因此,为了避免这一错误,使用了foreach循环的概念。可能还有其他优点,但这就是我认为使用foreach循环的主要概念和优点。
它看起来像这样。非常粗糙。
for (Iterator<String> i = someList.iterator(); i.hasNext(); )
System.out.println(i.next());
Sun文档中对每一项都有很好的描述。
代码应为:
import java.util.ArrayList;
import java.util.List;
public class ForLoopDemo {
public static void main(String[] args) {
List<String> someList = new ArrayList<String>();
someList.add("monkey");
someList.add("donkey");
someList.add("skeleton key");
// Iteration using For Each loop
System.out.println("Iteration using a For Each loop:");
for (String item : someList) {
System.out.println(item);
}
// Iteration using a normal For loop
System.out.println("\nIteration using normal For loop: ");
for (int index = 0; index < someList.size(); index++) {
System.out.println(someList.get(index));
}
}
}