Java For-Each Loop: Syntax, Examples, and Benefits

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

Introduce Java For Each Loop and give examples

回答:

The Java for-each loop, also known as the enhanced for loop, is a simplified way to iterate over arrays and collections in Java. It provides a more readable and concise syntax compared to the traditional for loop, making it easier to work with collections and arrays without the need for an index variable.

Syntax

The syntax of the for-each loop is as follows:

for (Type element : collection) {
    // Use the element
}
  • Type is the data type of the elements in the collection or array.
  • element is a variable that will hold each element of the collection during the iteration.
  • collection can be an array or any class that implements the Iterable interface (like ArrayList, HashSet, etc.).

Examples

Example 1: Iterating Over an Array

public class ForEachExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        // Using for-each loop to iterate over the array
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

1
2
3
4
5

Example 2: Iterating Over a List

import java.util.ArrayList;
import java.util.List;

public class ForEachListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Using for-each loop to iterate over the list
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry

Example 3: Iterating Over a Set

import java.util.HashSet;
import java.util.Set;

public class ForEachSetExample {
    public static void main(String[] args) {
        Set<String> colors = new HashSet<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Using for-each loop to iterate over the set
        for (String color : colors) {
            System.out.println(color);
        }
    }
}

Output:

Red
Green
Blue

(Note: The order of output may vary since HashSet does not maintain any order.)

Example 4: Iterating Over a Map

To iterate over a Map, you can use the entrySet() method:

import java.util.HashMap;
import java.util.Map;

public class ForEachMapExample {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 90);
        scores.put("Bob", 85);
        scores.put("Charlie", 92);

        // Using for-each loop to iterate over the map
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

Alice: 90
Bob: 85
Charlie: 92

Conclusion

The for-each loop is a powerful and convenient way to iterate over arrays and collections in Java. It enhances code readability and reduces the chances of errors associated with index management. However, it is important to note that the for-each loop does not allow modification of the collection during iteration (e.g., adding or removing elements).