DEV Community

Sudhakar V
Sudhakar V

Posted on

For-each in Java

In Java, for-each is a special form of the for loop designed to iterate over collections, arrays, or any Iterable objects. It is also known as the enhanced for loop.


🔹 Syntax of for-each Loop

for (datatype variable : collection) {
    // body of loop
}
Enter fullscreen mode Exit fullscreen mode
  • datatype: The type of elements in the collection or array.
  • variable: A temporary variable that holds the current element during each iteration.
  • collection: The array or collection to iterate over.

🔹 for-each with Arrays

public class ForEachArrayExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};

        for (int num : numbers) {
            System.out.println(num);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ Output:

10
20
30
40
Enter fullscreen mode Exit fullscreen mode

🔹 for-each with List

import java.util.*;

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

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ Output:

Apple
Banana
Cherry
Enter fullscreen mode Exit fullscreen mode

🔹 for-each with Set

import java.util.*;

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

        for (String color : colors) {
            System.out.println(color);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 for-each with Map (Indirectly)

Since a Map is not directly iterable with for-each, you use one of its views like entrySet(), keySet(), or values().

import java.util.*;

public class ForEachMapExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");

        // Iterating over entry set (key-value pairs)
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Limitations of for-each

Limitation Description
Cannot modify structure You can't use remove() directly during iteration. Use iterator instead.
No index access Unlike traditional for loops, you don't get the index.
Forward-only It only iterates in forward direction.

🔹 When to Use for-each?

Use it when:

  • You want to read/access every element in a collection.
  • You don't need the index.
  • You don’t need to remove or replace elements.

🔹 Example: Comparing Traditional vs for-each

String[] names = {"Alice", "Bob", "Charlie"};

// Traditional for loop
for (int i = 0; i < names.length; i++) {
    System.out.println("Name at index " + i + ": " + names[i]);
}

// Enhanced for-each loop
for (String name : names) {
    System.out.println("Name: " + name);
}
Enter fullscreen mode Exit fullscreen mode

Would you like a use-case involving a custom class or nested collections with for-each?

Top comments (0)