SwadhyAI Notes

All Java notes

How to Loop Through ArrayList in Java

The Challenge

Iterate through all elements in an ArrayList using different methods!

Solutions

Method 1: Using For-Each Loop

java
import java.util.ArrayList;

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

for (String fruit : fruits) {
    System.out.println(fruit);
}
// Output:
// Apple
// Banana
// Cherry

Method 2: Using Traditional For Loop

java
for (int i = 0; i < fruits.size(); i++) {
    System.out.println(fruits.get(i));
}

Method 3: Using Iterator

java
import java.util.Iterator;

Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

Method 4: Using forEach() with Lambda

java
fruits.forEach(fruit -> System.out.println(fruit));

// Or using method reference
fruits.forEach(System.out::println);

Method 5: Using Java 8 Streams

java
fruits.stream().forEach(System.out::println);

Did You Know?

The for-each loop is the most readable and recommended for simple iteration. Use Iterator when you need to remove elements during iteration!

Pro Tip

Use removeIf() for safe removal during iteration:

java
fruits.removeIf(fruit -> fruit.startsWith("B"));

Real-World Use Cases

  • Data processing: Process each item in a list
  • UI rendering: Display list items
  • Validation: Check each element
  • Transformation: Convert list elements
›Short versionOpen if you only have a minute.
  • A for-each loop is for reading. Removing inside it throws ConcurrentModificationException.
  • list.remove(index) inside an index loop skips the next element, because the later items shift left and i still increments.
  • removeIf deletes every match in one pass.
  • An Iterator and iterator.remove is the explicit form of a safe removal.

Loop an ArrayList

Visit each element, and remove some of them without skipping or throwing.

Working approach

  • Use for-each or forEach when the list structure stays the same.
  • Use an index loop when you need the index and you are not removing.
  • Use removeIf, or iterate backward, when elements disappear.

Walk the sample

  1. List Apple, Banana
  2. The loop binds Apple and prints it
  3. The loop binds Banana and prints it
  4. The list is unchanged

The trap

The enhanced for loop uses an iterator that notices a structural change and throws. The failure shows up on the next element, not on the remove line itself.

java
list.removeIf(String::isBlank);

// index loop that removes, walking backward so shifts do not skip
for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i).isBlank()) {
        list.remove(i);
    }
}

What happens in for (String s : list) if the body calls list.remove(s)?

The iterator's expected modification count no longer matches the list. The next iteration throws ConcurrentModificationException.

removeIf or iterator.remove updates that count. An index loop that removes at i and then does i++ also skips the element that slid into i.

A read-only scan is O(n) time. remove(i) on an ArrayList shifts the tail, so removing many items from the front is quadratic unless you use removeIf or an iterator.

Easy to get wrong

  • Removing inside a for-each loop.
  • Removing at i in a forward index loop without adjusting i.