考虑:
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);
});
其他回答
这里有一个答案,它不假定了解Java迭代器。它不太精确,但对教育有用。
在编程时,我们通常编写如下代码:
char[] grades = ....
for(int i = 0; i < grades.length; i++) { // for i goes from 0 to grades.length
System.out.print(grades[i]); // Print grades[i]
}
foreach语法允许以更自然、更少语法噪音的方式编写这种常见模式。
for(char grade : grades) { // foreach grade in grades
System.out.print(grade); // print that grade
}
此外,此语法对于不支持数组索引但实现Java Iterable接口的Lists或Set等对象有效。
还要注意,在原始问题中使用“foreach”方法确实有一些限制,例如在迭代过程中无法从列表中删除项目。
新的for循环更容易阅读,并且不需要单独的迭代器,但只有在只读迭代过程中才能真正使用。
nsayer的答案暗示了这一点,但值得注意的是,当“someList”是实现java.lang.Iterable的任何东西时,OP的for(..)语法都会起作用——它不必是列表,也不必是java.util的集合。因此,甚至您自己的类型也可以与此语法一起使用。
在Java8中,他们引入了forEach。使用它列表,可以循环地图。
使用for each循环列表
List<String> someList = new ArrayList<String>();
someList.add("A");
someList.add("B");
someList.add("C");
someList.forEach(listItem -> System.out.println(listItem))
or
someList.forEach(listItem-> {
System.out.println(listItem);
});
使用for each循环映射
Map<String, String> mapList = new HashMap<>();
mapList.put("Key1", "Value1");
mapList.put("Key2", "Value2");
mapList.put("Key3", "Value3");
mapList.forEach((key,value)->System.out.println("Key: " + key + " Value : " + value));
or
mapList.forEach((key,value)->{
System.out.println("Key : " + key + " Value : " + value);
});
代码应为:
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));
}
}
}