考虑:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
    System.out.println(item);
}

如果不使用for each语法,等价的for循环会是什么样子?


当前回答

每个习惯用法的Java只能应用于*Iterable类型的数组或对象。这个习惯用法是隐含的,因为它确实有迭代器支持。迭代器由程序员编程,通常使用整数索引或节点(取决于数据结构)来跟踪其位置。从理论上讲,它比常规的for循环慢,至少对于数组和列表等“线性”结构来说是这样,但它提供了更大的抽象性。

其他回答

在Java 8之前,您需要使用以下功能:

Iterator<String> iterator = someList.iterator();

while (iterator.hasNext()) {
    String item = iterator.next();
    System.out.println(item);
}

然而,通过在Java8中引入Streams,您可以用更少的语法完成同样的任务。例如,对于someList,您可以执行以下操作:

someList.stream().forEach(System.out::println);

你可以在这里找到更多关于溪流的信息。

Java“for each”循环构造将允许对两种类型的对象进行迭代:

T[](任何类型的数组)java.lang.Iterable<T>

Iterable<T>接口只有一个方法:Iterator<T>迭代器()。这对Collection<T>类型的对象有效,因为Collection<T<接口扩展了Iterable<T>。

这看起来很疯狂,但嘿,它奏效了

List<String> someList = new ArrayList<>(); //has content
someList.forEach(System.out::println);

这是可行的。魔术

在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);
});

foreach循环语法为:

for (type obj:array) {...}

例子:

String[] s = {"Java", "Coffe", "Is", "Cool"};
for (String str:s /*s is the array*/) {
    System.out.println(str);
}

输出:

Java
Coffe
Is
Cool

警告:可以使用foreach循环访问数组元素,但不能初始化它们。为此使用原始for循环。

警告:必须将数组的类型与其他对象匹配。

for (double b:s) // Invalid-double is not String

如果要编辑元素,请使用原始for循环,如下所示:

for (int i = 0; i < s.length-1 /*-1 because of the 0 index */; i++) {
    if (i==1) //1 because once again I say the 0 index
        s[i]="2 is cool";
    else
        s[i] = "hello";
}

现在,如果我们将数据转储到控制台,我们会得到:

hello
2 is cool
hello
hello