Java for-each Loop

In this lesson of our Java course, we will look the Java for-each loop. A Java for-each loop, also known as a “enhanced for loop”, is a control flow statement in Java that allows you to iterate over a sequence, such as an array or a list, and perform a set of instructions for each element in the sequence. The for-each loop is like the for loop, but it is more concise and easier to read, as it eliminates the need to manage the loop counter and exit condition.

1. Java for-each loop Syntax

Let’s look at the for-each loop syntax.

for (variable : collection) {
    // code to be executed
}
  1. The variable is the name of a new variable that will hold the current element of the collection.
  2. The collection can be an array or an instance of any class that implements the Iterable interface, such as a List or a Set.

2. How Java for-each loop works?

Let’s look at the below flow chart for better understanding of the for-each loop:

Java for-each Loop
How for-each Loop Works in Java

3. for-each Loop Example

Here’s an example of a for-each loop in Java that iterates over a list of strings and prints each element:

import java.util.*;

class JavaForEachLoop {
    public static void main(String[] args) {
        List < String > names = Arrays.asList("John", "Jane", "Bob");

        for (String name: names) {
            System.out.println(name);
        }
    }
}

In this example, the loop starts by initializing the variable name to the first element of the names list. The code inside the loop prints the value of the name. On each iteration, the variable name is updated to the next element of the names list. Once there are no more elements in the list, the loop exits.The output of this example will be:

John 
Jane 
Bob

Here is another example of our Java for-each loop to provide you better understanding:

import java.util.*;
class JavaForEachLoop {
    public static void main(String[] args) {
        Map < String, Integer > ages = new HashMap < > ();
        ages.put("John", 25);
        ages.put("Jane", 30);
        ages.put("Bob", 35);

        for (Map.Entry < String, Integer > entry: ages.entrySet()) {
            System.out.println(entry.getKey() + " is " + entry.getValue() + " years old.");
        }

    }
}

In this example, the loop starts by initializing the variable entry to the first entry of the ages map. The code inside the loop prints the key and the value of entry. On each iteration, the variable entry is updated to the next entry of the ages map. Once there are no more entries in the map, the loop exits.The output of this example will be:

John is 25 years old.
Jane is 30 years old.
Bob is 35 years old.

In this example, the for-each loop is used to iterate over the entry set of a map. The <a href="https://javadevjournal.com/java/java-streams-map-examples/" data-type="post" data-id="4296">entrySet()</a> method of the Map interface returns a set of Map.Entry objects that represent the key-value pairs in the map. The Map.Entry interface defines the getKey() and getValue() methods that can access the key and value of an entry.

Don’t worry if you are not sure what is Map and other interfaces are . We will cover them in details during this course. Let’s continue to focus on how loop works.

The for-each loop can also iterate over the key set and the value collection of a map, using the keySet() and values() methods, respectively.

import java.util.*;

class JavaForEachLoop {
    public static void main(String[] args) {
        
        for (String name: ages.keySet()) {
            System.out.println("Name : " + name);
        }

        for (Integer age: ages.values()) {
            System.out.println("Age : " + age);
        }
    }
}

Summary

The Java for-each loop is a powerful control flow statement that allows you to iterate over sequences and perform repetitive tasks in Java. The syntax, flowchart, and example provided above should give you a good understanding of how to use the for-each loop in your Java programs.

The for-each loop is a convenient alternative to the for loop, as it eliminates the need to manage the loop counter and exit condition and it’s more readable. It’s a good idea to use for-each loop when you just need to iterate over a collection with no index variable. The source code for this course is available on our GitHub Repository.