Language 3 of 10 · Topic 0.6

Control Flow: Loops, Enhanced For-Each & Streams Iteration

1Concept

Java provides standard for, while, and do-while loops, alongside Enhanced For-Each (for (T item : iterable)) and functional Streams (list.stream().forEach()).

2Architecture Diagram

for (String item : list) ──► Internally uses Iterator<T> hasNext() and next()

3Code Example

Stage 0 Language Foundations
import java.util.List;

public class LoopsDemo {
    public static void main(String[] args) {
        var languages = List.of("Java", "C#", "C++", "Python", "Go");

        System.out.println("=== Enhanced For-Each Loop ===");
        for (var lang : languages) {
            if (lang.equals("C++")) continue;
            System.out.println("Tech: " + lang);
        }

        System.out.println("\n=== While Loop with Break ===");
        int attempts = 0;
        while (attempts < 5) {
            attempts++;
            if (attempts == 3) {
                System.out.println("Connected at attempt #" + attempts);
                break;
            }
        }
    }
}

4Expected Output

=== Enhanced For-Each Loop ===
Tech: Java
Tech: C#
Tech: Python
Tech: Go

=== While Loop with Break ===
Connected at attempt #3

5Key Takeaways

  • Do not mutate a collection while iterating over it with a for-each loop (throws ConcurrentModificationException).
  • Use Iterator.remove() or collection.removeIf() for safe filtering during iteration.
  • For primitive performance without boxing, use primitive loops (int i = 0; i < n; i++).