Java For Loop – Java For Loop

最后修改: 2020年 1月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll look at a core aspect of the Java language – executing a statement or a group of statements repeatedly using a for loop.

在这篇文章中,我们将研究Java语言的一个核心方面–使用for循环重复执行一条或一组语句。

2. Simple for Loop

2.简单的for循环

A for loop is a control structure that allows us to repeat certain operations by incrementing and evaluating a loop counter.

一个for 循环是一个控制结构,它允许我们通过增加和评估一个循环计数器来重复某些操作。

Before the first iteration, the loop counter gets initialized, then the condition evaluation is performed followed by the step definition (usually a simple incrementation).

在第一次迭代之前,循环计数器被初始化,然后进行条件评估,接着是步骤定义(通常是简单的递增)。

The syntax of the for loop is:

for 循环的语法是。

for (initialization; Boolean-expression; step) 
  statement;

Let’s see it in a simple example:

让我们在一个简单的例子中看到它。

for (int i = 0; i < 5; i++) {
    System.out.println("Simple for loop: i = " + i);
}

The initialization, Boolean-expression, and step used in for statements are optional. Here’s an example of an infinite for loop:

for语句中使用的初始化布尔表达式步骤是可选的。下面是一个无限for循环的例子。

for ( ; ; ) {
    // Infinite for loop
}

2.1. Labeled for Loops

2.1.标记的for循环

We can also have labeled for loops. It’s useful if we’ve got nested for loops so that we can break/continue from aspecific for loop:

我们也可以有标记的for循环。如果我们有嵌套的for循环,这很有用,这样我们就可以从特定的for循环中break/continue

aa: for (int i = 1; i <= 3; i++) {
    if (i == 1)
      continue;
    bb: for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break aa;
        }
        System.out.println(i + " " + j);
    }
}

3. Enhanced for Loop

3.增强的for循环

Since Java 5, we have a second kind of for loop called the enhanced for which makes it easier to iterate over all elements in an array or a collection.

从Java 5开始,我们有了第二种for循环,叫做enhanced for,它使我们更容易遍历数组或集合中的所有元素。

The syntax of the enhanced for loop is:

增强的for循环的语法是。

for(Type item : items)
  statement;

Since this loop is simplified in comparison to the standard for loop, we need to declare only two things when initializing a loop:

由于这个循环与标准的for循环相比是简化的,所以在初始化循环时我们只需要声明两件事。

  1. The handle for an element we’re currently iterating over
  2. The source array/collection we’re iterating

Therefore, we can say that: For each element in items, assign the element to the item variable and run the body of the loop.

因此,我们可以这样说。对于items中的每个元素,将该元素分配给item变量并运行循环的主体

Let’s have a look at the simple example:

让我们看一下这个简单的例子。

int[] intArr = { 0,1,2,3,4 }; 
for (int num : intArr) {
    System.out.println("Enhanced for-each loop: i = " + num);
}

We can use it to iterate over various Java data structures:

我们可以用它来迭代各种Java数据结构。

Given a List<String> list object – we can iterate it:

给定一个List<String> list对象–我们可以对其进行迭代。

for (String item : list) {
    System.out.println(item);
}

We can similarly iterate over a Set<String> set:

我们同样可以在一个Set<String>集合上进行迭代

for (String item : set) {
    System.out.println(item);
}

And, given a Map<String,Integer> map we can iterate over it as well:

而且,给定一个Map<String,Integer> map,我们也可以对它进行迭代。

for (Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(
      "Key: " + entry.getKey() + 
      " - " + 
      "Value: " + entry.getValue());
}

3.1. Iterable.forEach()

3.1.Iterable.forEach()

Since Java 8, we can leverage for-each loops in a slightly different way. We now have a dedicated forEach() method in the Iterable interface that accepts a lambda expression representing an action we want to perform.

从Java 8开始,我们可以用一种稍微不同的方式来利用for-each循环。我们现在在Iterable接口中有一个专门的forEach()方法,它接受一个代表我们要执行的动作的lambda表达式。

Internally, it simply delegates the job to the standard loop:

在内部,它只是将这项工作委托给标准循环。

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Let’s have a look at the example:

让我们看一下这个例子。

List<String> names = new ArrayList<>();
names.add("Larry");
names.add("Steve");
names.add("James");
names.add("Conan");
names.add("Ellen");

names.forEach(name -> System.out.println(name));

4. Conclusion

4.结论

In this quick tutorial, we explored Java’s for loop.

在这个快速教程中,我们探讨了Java的for循环。

As always, examples can be found over on GitHub.

一如既往,可以在GitHub上找到实例