Skip to lesson

Looping through a list

There are four common ways to visit every item of a list: an index loop, a for-each loop, an Iterator, and forEach with a lambda. This lesson reads and changes items; removing items while you loop has its own lesson next.

Pick the loop for the job

A for-each loop, written for (String s : list), visits every item of a list in order and puts each item in a variable for you. It is the simplest way to read every item, but it does not give you the index.

All four loops visit items from index 0 to the end, in order. They differ in what you get inside the loop and what you can change.

Use the simplest one that does the job: most loops only read, so for-each is usual.

Example 1 · Three ways to read every item

ProductLoopsDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ProductLoopsDemo {    public static void main(String[] args) {        List<String> products = new ArrayList<>(List.of("Pen", "Notebook", "Bag"));
        System.out.println("Index loop:");        for (int i = 0; i < products.size(); i++) {            System.out.println((i + 1) + ". " + products.get(i));        }
        System.out.println("For-each:");        for (String name : products) {            System.out.println("In stock: " + name);        }
        System.out.println("forEach with a lambda:");        products.forEach(name -> System.out.println("Hi " + name));    }}
Output
Index loop:
1. Pen
2. Notebook
3. Bag
For-each:
In stock: Pen
In stock: Notebook
In stock: Bag
forEach with a lambda:
Hi Pen
Hi Notebook
Hi Bag

What this code does

  • The index loop is the only one that gives you the position, so it can print 1., 2., 3..
  • For-each and forEach give you only the item. They are shorter and leave no room for index mistakes.

Which loop for which job:

  • Index loop for (int i = 0; i < list.size(); i++) → when you need the position, or want to set items
  • For-each for (String s : list) → the simplest way to read every item
  • Iterator → when you need to remove items while looping (next lesson)
  • list.forEach(s -> ...) → a short way to run one action for each item

The index loop: when position matters

An index loop gives you i, so you can number the items, find where the biggest one sits, or compare an item with its neighbour. For-each cannot do any of these.

Example 2 · Index loop: the dearest product and its position

DearestProductDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class DearestProductDemo {    public static void main(String[] args) {        List<Integer> prices = new ArrayList<>(List.of(450, 1200, 90, 3000, 799));
        int best = 0;        for (int i = 1; i < prices.size(); i++) {            if (prices.get(i) > prices.get(best)) {                best = i;            }        }        System.out.println("Dearest: Rs. " + prices.get(best) + " at index " + best);
        for (int i = 1; i < prices.size(); i++) {            int change = prices.get(i) - prices.get(i - 1);            System.out.println("Item " + i + " vs item " + (i - 1) + ": " + change);        }    }}
Output
Dearest: Rs. 3000 at index 3
Item 1 vs item 0: 750
Item 2 vs item 1: -1110
Item 3 vs item 2: 2910
Item 4 vs item 3: -2201

What this code does

  • best stores an index, not a price, so the program can report both the price and where it sits.
  • The second loop starts at 1 so that i - 1 is always a valid index: each item is compared with the one before it.
  • A for-each loop could not do either job, because it never tells you the index.

Start at 0 and stop before size(). A loop that runs to i <= list.size() goes one step too far and throws IndexOutOfBoundsException.

To walk backwards, start at size() - 1 and count down to 0.

A for-each loop is an Iterator in disguise

The compiler turns for (String p : products) into an iterator loop with hasNext() and next() calls. You get the same items in the same order, with less to write.

Example 3 · For-each is an Iterator in disguise

SameLoopDemo.javaJava
import java.util.ArrayList;import java.util.Iterator;import java.util.List;
public class SameLoopDemo {    public static void main(String[] args) {        List<String> products = new ArrayList<>(List.of("Pen", "Notebook", "Bag"));
        for (String p : products) {            System.out.println("for-each: " + p);        }
        Iterator<String> it = products.iterator();        while (it.hasNext()) {            String p = it.next();            System.out.println("iterator: " + p);        }    }}
Output
for-each: Pen
for-each: Notebook
for-each: Bag
iterator: Pen
iterator: Notebook
iterator: Bag

What this code does

  • Both loops print the same items in the same order.
  • hasNext() asks whether another item is left; next() returns it and moves forward. A for-each loop writes these calls for you.

An iterator is a small object that walks a collection one item at a time. You rarely need to write one by hand for reading. The next lesson shows the one job that needs it: removing items safely while looping.

Changing items: set and replaceAll

In for (int m : marks) { m = m + 5; }, m is a local copy. Changing it does not change the list.

Example 4 · Changing items: delivery fee

DeliveryFeeDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class DeliveryFeeDemo {    public static void main(String[] args) {        List<Integer> prices = new ArrayList<>(List.of(450, 1200, 90));
        for (int p : prices) {            p = p + 50;        }        System.out.println("After for-each: " + prices);
        for (int i = 0; i < prices.size(); i++) {            prices.set(i, prices.get(i) + 50);        }        System.out.println("After set: " + prices);
        prices.replaceAll(p -> Math.min(p + 50, 1500));        System.out.println("After replaceAll: " + prices);    }}
Output
After for-each: [450, 1200, 90]
After set: [500, 1250, 140]
After replaceAll: [550, 1300, 190]

What this code does

  • In the for-each loop, p is a local copy of each price. Changing it leaves the list as it was.
  • set(i, ...) writes the new value back into the list at the same index.
  • replaceAll does that for every item; here Math.min also keeps each price at 1500 or below.

To change items in place, use an index loop with set(i, newValue), or replaceAll with a lambda: marks.replaceAll(m -> m + 5);. The lambda gets each item and returns its new value.

Find the bug

Find the loop bug

Each snippet should work. Tap the wrong line, then check the fix.

Add Rs. 50 delivery to every price in the list.

Round 1 of 4

forEach is for reading

list.forEach(item -> ...) runs one action for each item. It reads each item; it does not change the list.

Example 5 · forEach reads each item

ForEachDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ForEachDemo {    public static void main(String[] args) {        List<Integer> prices = new ArrayList<>(List.of(450, 1200, 90));
        prices.forEach(p -> System.out.println("Price: Rs. " + p));        prices.forEach(System.out::println);
        int total = 0;        for (int p : prices) {            total = total + p;        }        System.out.println("Total: Rs. " + total);    }}
Output
Price: Rs. 450
Price: Rs. 1200
Price: Rs. 90
450
1200
90
Total: Rs. 1740

What this code does

  • forEach runs the lambda once for each item. System.out::println is a shorter way to write p -> System.out.println(p).
  • The total uses a plain for-each loop: a lambda cannot change the local variable total, so sums are easier with a loop.

A lambda cannot change a local variable of the method around it, and adding or removing items inside a forEach lambda throws ConcurrentModificationException. For sums, counts and changes, a for-each loop, an index loop or replaceAll is simpler.

Next step

Check your understanding

11 quick questions