Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. Enhanced for / for-each (Java)

Enhanced for / for-each (Java)

Syntax for processing every element of a collection or array in sequence. Java's enhanced for loop (for-each loop) lets you express "take each element one by one and process it" concisely, without writing an index variable. Internally it uses the Iterable interface, so any collection that implements Iterable — including arrays, ArrayList, and HashSet — can be iterated with the same syntax. This page also covers how to handle cases where an index is needed (using IntStream.range() or switching to a traditional for loop).

Syntax

// Basic enhanced for loop (for-each) syntax
for (ElementType varName : arrayOrCollection) {
    // Each element is assigned to varName in turn and processed
}

// Example with an array
for (String item : array) {
    System.out.println(item);
}

// Example with an ArrayList (implements Iterable, so the same syntax works)
for (String item : list) {
    System.out.println(item);
}

// When an index is also needed, use IntStream.range() (Java 8+)
IntStream.range(0, list.size()).forEach(i -> {
    System.out.println(i + ": " + list.get(i));
});

// Or switch to a traditional for loop
for (int i = 0; i < array.length; i++) {
    System.out.println(i + ": " + array[i]);
}

Characteristics of the Enhanced for Loop

ItemDescription
Applicable targetsArrays and any collection that implements Iterable<T> (ArrayList, HashSet, LinkedList, etc.).
Traversal directionForward only — from first to last. Use a traditional for loop to iterate in reverse.
IndexNot available. When an index is needed, use IntStream.range() or a traditional for loop.
Modifying elementsReassigning the loop variable does not affect the original array or collection. Use a traditional for loop to overwrite elements.
Removing elements during iterationCalling remove() on the collection inside an enhanced for loop throws a ConcurrentModificationException. Use Iterator or removeIf() instead.

Sample Code

ForEachArray.java
public class ForEachArray {
    public static void main(String[] args) {

        // --- Enhanced for loop over an array ---
        // Managing KOF entry fighters with an array
        String[] fighters = {"草薙京", "八神庵", "テリー・ボガード", "不知火舞", "K'"};

        // The enhanced for loop retrieves one element at a time from the beginning.
        // No index variable is needed, so the intent is communicated simply.
        System.out.println("=== Entry Fighter List ===");
        for (String name : fighters) {
            System.out.println("・" + name);
        }

        // --- Enhanced for loop over an int array ---
        // Power levels for each fighter
        int[] power = {1800, 1700, 1600, 1500, 1900};

        int total = 0;
        for (int p : power) {
            total += p; // Accumulate the total
        }
        System.out.println("Total power: " + total);
        System.out.println("Average power: " + (total / power.length));
    }
}
javac ForEachArray.java
java ForEachArray
=== Entry Fighter List ===
・草薙京
・八神庵
・テリー・ボガード
・不知火舞
・K'
Total power: 8500
Average power: 1700
ForEachCollection.java
import java.util.ArrayList;
import java.util.HashSet;

public class ForEachCollection {
    public static void main(String[] args) {

        // --- Enhanced for loop over an ArrayList ---
        // Managing KOF team members with a list
        ArrayList<String> teamJapan = new ArrayList<>();
        teamJapan.add("草薙京");
        teamJapan.add("二階堂紅丸");
        teamJapan.add("大門五郎");

        // ArrayList also implements Iterable, so the same syntax as arrays works
        System.out.println("=== Team Japan ===");
        for (String member : teamJapan) {
            System.out.println("Member: " + member);
        }

        // --- Enhanced for loop over a HashSet ---
        // Managing participating teams with a set (no duplicates)
        HashSet<String> teams = new HashSet<>();
        teams.add("チーム日本");
        teams.add("チームボガード");
        teams.add("チームヤガミ");
        teams.add("チーム日本"); // Duplicates are ignored

        // HashSet does not guarantee iteration order, but the enhanced for loop still works
        System.out.println("=== Participating Teams ===");
        for (String team : teams) {
            System.out.println("・" + team);
        }
    }
}
javac ForEachCollection.java
java ForEachCollection
=== Team Japan ===
Member: 草薙京
Member: 二階堂紅丸
Member: 大門五郎
=== Participating Teams ===
・チームボガード
・チーム日本
・チームヤガミ

The iteration order of a HashSet varies by runtime environment and JVM version. The output above is just one example; the actual order may differ.

ForEachWithIndex.java
import java.util.ArrayList;
import java.util.stream.IntStream;

public class ForEachWithIndex {
    public static void main(String[] args) {

        // KOF ranking list
        ArrayList<String> ranking = new ArrayList<>();
        ranking.add("草薙京");
        ranking.add("K'");
        ranking.add("八神庵");
        ranking.add("テリー・ボガード");
        ranking.add("不知火舞");

        // --- Option 1: Use IntStream.range() to get the index (Java 8+) ---
        // Keeps the simplicity of an enhanced for loop while also providing the index
        System.out.println("=== Ranking (IntStream.range) ===");
        IntStream.range(0, ranking.size()).forEach(i -> {
            System.out.println("#" + (i + 1) + ": " + ranking.get(i));
        });

        // --- Option 2: Traditional for loop (baseline when an index is needed) ---
        // Use this for reverse order, custom step, or other flexible traversal
        System.out.println("=== Ranking (reverse, traditional for loop) ===");
        for (int i = ranking.size() - 1; i >= 0; i--) {
            System.out.println("#" + (i + 1) + ": " + ranking.get(i));
        }

        // --- Reassigning the loop variable in an enhanced for loop does not affect the original list ---
        // The loop variable name is a copy of the element. Reassigning it has no effect on ranking.
        System.out.println("=== Reassignment does not change the original list ===");
        for (String name : ranking) {
            name = "test"; // Has no effect on ranking
        }
        System.out.println("First element of ranking: " + ranking.get(0)); // Still 草薙京
    }
}
javac ForEachWithIndex.java
java ForEachWithIndex
=== Ranking (IntStream.range) ===
#1: 草薙京
#2: K'
#3: 八神庵
#4: テリー・ボガード
#5: 不知火舞
=== Ranking (reverse, traditional for loop) ===
#5: 不知火舞
#4: テリー・ボガード
#3: 八神庵
#2: K'
#1: 草薙京
First element of ranking: 草薙京
ForEachIterable.java
import java.util.Iterator;
import java.util.ArrayList;

public class ForEachIterable {
    public static void main(String[] args) {

        // --- Understanding how Iterable works ---
        // The enhanced for loop internally uses an Iterator to traverse the collection.
        // The code below is equivalent to an enhanced for loop.

        ArrayList<String> fighters = new ArrayList<>();
        fighters.add("草薙京");
        fighters.add("八神庵");
        fighters.add("テリー・ボガード");

        // Enhanced for loop (concise)
        System.out.println("=== Enhanced for loop ===");
        for (String name : fighters) {
            System.out.println(name);
        }

        // Equivalent Iterator-based code (what the enhanced for loop expands to after compilation)
        System.out.println("=== Iterator (what the enhanced for loop compiles to) ===");
        Iterator<String> it = fighters.iterator();
        while (it.hasNext()) {
            String name = it.next();
            System.out.println(name);
        }

        // --- To remove elements during iteration, use Iterator.remove() ---
        // Calling fighters.remove() inside an enhanced for loop throws ConcurrentModificationException.
        // Use Iterator or removeIf() for safe removal.
        System.out.println("=== Remove with Iterator (excluding 八神庵) ===");
        Iterator<String> it2 = fighters.iterator();
        while (it2.hasNext()) {
            String name = it2.next();
            if (name.equals("八神庵")) {
                it2.remove(); // Safe to remove via the Iterator
            }
        }
        System.out.println("After removal: " + fighters);

        // removeIf() provides an even more concise way to do this (Java 8+)
        fighters.removeIf(name -> name.equals("草薙京"));
        System.out.println("After removeIf: " + fighters);
    }
}
javac ForEachIterable.java
java ForEachIterable
=== Enhanced for loop ===
草薙京
八神庵
テリー・ボガード
=== Iterator (what the enhanced for loop compiles to) ===
草薙京
八神庵
テリー・ボガード
=== Remove with Iterator (excluding 八神庵) ===
After removal: [草薙京, テリー・ボガード]
After removeIf: [テリー・ボガード]

Choosing a Traversal Method

SituationCommon approach
Process all elements in order (no index needed)Enhanced for loop (simplest)
Need the index as wellIntStream.range(0, size).forEach(i -> ...) (Java 8+)
Reverse order, custom step, or mid-traversal modification neededTraditional for loop
Need to remove elements during iterationIterator.remove() or removeIf()
Functional-style processingstream().forEach() (Stream API)

Common Mistake 1: Calling remove() inside an enhanced for loop causes ConcurrentModificationException

The enhanced for loop uses an Iterator internally to traverse the collection. Directly modifying the collection with remove() during traversal causes the Iterator to detect the modification and throw a ConcurrentModificationException.

ForEachRemoveNg.java
import java.util.ArrayList;

public class ForEachRemoveNg {
    public static void main(String[] args) {
        ArrayList<String> fighters = new ArrayList<>();
        fighters.add("草薙京");
        fighters.add("八神庵");
        fighters.add("テリー・ボガード");

        // Modifying the collection inside an enhanced for loop throws an exception
        for (String name : fighters) {
            if (name.equals("八神庵")) {
                fighters.remove(name); // ConcurrentModificationException is thrown
            }
        }
    }
}
javac ForEachRemoveNg.java
java ForEachRemoveNg
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at ForEachRemoveNg.main(ForEachRemoveNg.java:12)

To remove elements during iteration, use Iterator.remove() or removeIf() (Java 8+).

ForEachRemoveOk.java
import java.util.ArrayList;
import java.util.Iterator;

public class ForEachRemoveOk {
    public static void main(String[] args) {
        ArrayList<String> fighters = new ArrayList<>();
        fighters.add("草薙京");
        fighters.add("八神庵");
        fighters.add("テリー・ボガード");

        // Iterator.remove() allows safe removal during iteration
        Iterator<String> it = fighters.iterator();
        while (it.hasNext()) {
            if (it.next().equals("八神庵")) {
                it.remove();
            }
        }
        System.out.println("After Iterator.remove(): " + fighters);

        // In Java 8+, removeIf() is even more concise
        fighters.removeIf(name -> name.equals("草薙京"));
        System.out.println("After removeIf(): " + fighters);
    }
}
javac ForEachRemoveOk.java
java ForEachRemoveOk
After Iterator.remove(): [草薙京, テリー・ボガード]
After removeIf(): [テリー・ボガード]

Common Mistake 2: Assuming that reassigning the loop variable changes the original collection

The loop variable of an enhanced for loop is a "copy (a copy of the reference)" of each element. Reassigning the loop variable to a different value does not change the contents of the original array or collection.

ForEachReassignNg.java
import java.util.ArrayList;

public class ForEachReassignNg {
    public static void main(String[] args) {
        ArrayList<String> fighters = new ArrayList<>();
        fighters.add("草薙京");
        fighters.add("八神庵");
        fighters.add("テリー・ボガード");

        // Reassigning the loop variable does not affect the list
        for (String name : fighters) {
            name = "K'"; // Has no effect on the list
        }

        System.out.println(fighters); // Unchanged
    }
}
javac ForEachReassignNg.java
java ForEachReassignNg
[草薙京, 八神庵, テリー・ボガード]

To overwrite elements in the original list, use a traditional for loop and assign via the index.

ForEachReassignOk.java
import java.util.ArrayList;

public class ForEachReassignOk {
    public static void main(String[] args) {
        ArrayList<String> fighters = new ArrayList<>();
        fighters.add("草薙京");
        fighters.add("八神庵");
        fighters.add("テリー・ボガード");

        // Use set() to replace elements by index
        for (int i = 0; i < fighters.size(); i++) {
            if (fighters.get(i).equals("八神庵")) {
                fighters.set(i, "K'");
            }
        }

        System.out.println(fighters); // [草薙京, K', テリー・ボガード]
    }
}
javac ForEachReassignOk.java
java ForEachReassignOk
[草薙京, K', テリー・ボガード]

Notes

The enhanced for loop (for-each loop) is syntax for iterating over arrays and collections that implement Iterable. Because you can express "take out all elements and process them" without writing index variables, the code reads more clearly.

Internally, the iterator() method of java.lang.Iterable is called, and the code is expanded at compile time into a loop that repeatedly calls hasNext() and next() on the Iterator. As a result, the enhanced for loop also works with custom classes that implement Iterable<T>.

Reassigning the loop variable does not change the contents of the original array or collection. To overwrite elements, use a traditional for loop and assign directly via the index. Also, removing elements from a collection with remove() during iteration throws a ConcurrentModificationException. Use Iterator.remove() or Collection.removeIf() instead.

For full traversal without an index, use an enhanced for loop; when an index is needed, use a traditional for loop or IntStream.range(); for functional-style processing, use stream().forEach() — choosing the right tool makes the intent of the code clear. For the basics of the for loop, see for loop. For forEach() in the Stream API, see Stream forEach / reduce.

If you find any errors or copyright issues, please .