Sub topic 5
Looping Over Collections
You now know how to put elements into a list. The next step is to visit each one, so you can print it, add it to a total, or check it. To loop over a collection means to visit its elements one at a time, in turn. This chapter shows the main ways to do that in Java: the for-each loop, the index loop, the Iterator, and the forEach method.
Why looping matters
Most real work with a collection happens inside a loop. Here are some examples:
- Printing every name in a list of students.
- Adding up every price in a shopping cart.
- Finding the longest word in a list of words.
- Checking whether any order is still unpaid.
Each of these tasks needs the same pattern: start at the first element, do something with it, move to the next one, and stop at the end.
The for-each loop
The for-each loop is the simplest way to visit every element. It is also called the enhanced for loop. You read it as "for each item in the collection, do this."
import java.util.ArrayList;
import java.util.List;
public class ForEachDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ana", "Ben", "Cara"));
for (String name : names) {
System.out.println("Hello, " + name);
}
// Hello, Ana
// Hello, Ben
// Hello, Cara
}
}Here is how to read the line for (String name : names):
Stringis the type of each element. It matches the type inList<String>.nameis a variable. It holds the current element on each pass of the loop.- The colon
:means "in". namesis the collection you loop over.
You don't need an index or a counter, and you don't need to know the size. The loop starts at the first element and stops after the last one.
Using for-each to compute a result
Loops often build up an answer as they go. This program adds up a list of prices and finds the largest one.
import java.util.ArrayList;
import java.util.List;
public class TotalDemo {
public static void main(String[] args) {
List<Double> prices = new ArrayList<>(List.of(4.50, 12.00, 3.25));
double total = 0;
double max = prices.get(0);
for (double p : prices) {
total += p;
if (p > max) {
max = p;
}
}
System.out.println("Total: " + total); // Total: 19.75
System.out.println("Max: " + max); // Max: 12.0
}
}The loop variable is a double, but the list holds Double objects. Java converts each one for you. The next chapter on wrapper types explains this conversion.
for-each works on more than lists
The for-each loop works on any Iterable. An Iterable is an interface for things that can hand out their elements one by one. Every List and every Set is an Iterable, and the loop also works on plain arrays.
import java.util.HashSet;
import java.util.Set;
public class SetLoopDemo {
public static void main(String[] args) {
Set<String> colors = new HashSet<>(Set.of("red", "green", "blue"));
for (String c : colors) {
System.out.println(c);
}
int[] scores = {90, 75, 88};
for (int s : scores) {
System.out.println(s);
}
}
}A Map is not an Iterable, so you cannot write for (x : someMap) directly. A later chapter, "Walking Through a Map," shows how to loop over maps.
The index loop
A List gives every element a position number, called an index. The first index is 0. You can loop over the indexes with a classic for loop and call get(i) to read each element.
import java.util.ArrayList;
import java.util.List;
public class IndexLoopDemo {
public static void main(String[] args) {
List<String> steps = new ArrayList<>(List.of("Wash", "Cut", "Cook"));
for (int i = 0; i < steps.size(); i++) {
System.out.println((i + 1) + ". " + steps.get(i));
}
// 1. Wash
// 2. Cut
// 3. Cook
}
}Use the index loop when you need the position number itself. Two examples are numbering the output or comparing an element with the one next to it.
The index loop only works on a List. A Set has no positions, so it has no get(i) method.
The Iterator
An Iterator is an object that walks through a collection one step at a time. You get one by calling iterator() on any list or set. It has two main methods:
hasNext()returnstrueif there is another element to visit.next()returns that next element and moves forward one step.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorDemo {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>(List.of("apple", "kiwi", "plum"));
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String f = it.next();
System.out.println(f.toUpperCase());
}
// APPLE
// KIWI
// PLUM
}
}You might ask why you would write this longer form. The for-each loop uses an Iterator behind the scenes. Java turns your for-each loop into something very close to the code above. Writing the Iterator yourself gives you one extra power: its remove() method can delete the current element safely. The next chapter covers that.
A common Iterator mistake
Call next() only once in each pass of the loop. Every call moves the iterator forward. This code is wrong:
import java.util.Iterator;
import java.util.List;
public class DoubleNextBug {
public static void main(String[] args) {
List<String> words = List.of("a", "b", "c");
Iterator<String> it = words.iterator();
while (it.hasNext()) {
System.out.println(it.next() + " has length " + it.next().length());
}
}
}The first pass reads "a" and then "b", so it skips an element. The second pass reads "c" and then calls next() again with nothing left. That throws NoSuchElementException. To fix it, call next() once, store the result in a variable, and use that variable.
The forEach method
Since Java 8, every Iterable has a forEach method. You give it a lambda, which is a short piece of code to run for each element.
import java.util.ArrayList;
import java.util.List;
public class ForEachMethodDemo {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(List.of("Lima", "Oslo", "Rome"));
cities.forEach(city -> System.out.println("City: " + city));
cities.forEach(System.out::println);
}
}The arrow -> separates the variable name (city) from the code to run. The second form, System.out::println, is a method reference. It is a shorter way to say "call println on each element."
forEach reads well for simple, one-line actions. For longer logic, or when you need break or return to leave the loop early, use a regular for-each loop.
Choosing a loop style
| Style | Works on | Gives index? | Can stop early with break? | Best for |
|---|---|---|---|---|
| for-each loop | List, Set, arrays | No | Yes | Most everyday loops |
| Index loop | List, arrays | Yes | Yes | When you need the position |
| Iterator | List, Set | No | Yes | Removing elements while looping |
| `forEach` method | List, Set | No | No | Short one-line actions |
Don't change the collection inside a for-each loop
A for-each loop is for reading. If you call names.add(...) or names.remove(...) on the list while a for-each loop is walking through it, Java usually throws ConcurrentModificationException. That error means the collection changed while an iterator was in the middle of using it. The next chapter explains why this happens and shows the safe ways to remove elements.
Exercises
Exercise
Write a for-each loop that prints only the words longer than 4 letters from List<String> words = List.of("cat", "planet", "sun", "rocket").
Show answer
for (String w : words) { if (w.length() > 4) { System.out.println(w); } } prints "planet" and "rocket".
Exercise
You have a HashSet<String> called tags. Can you loop over it with for (int i = 0; i < tags.size(); i++) and tags.get(i)? Why or why not?
Show answer
No. A Set has no index positions, so it has no get(int) method and the code will not compile. Use a for-each loop or an Iterator instead.
Exercise
What is wrong with this loop, and how do you fix it? while (it.hasNext()) { if (it.next().isEmpty()) { System.out.println("empty: " + it.next()); } }
Show answer
It calls next() twice in one pass. The second call skips an element and can throw NoSuchElementException. Fix it by storing the element first: String s = it.next(); if (s.isEmpty()) { System.out.println("empty: " + s); }
Exercise
Using an index loop, print each element of List<String> letters = List.of("x", "y", "z") together with its index, like "0: x".
Show answer
for (int i = 0; i < letters.size(); i++) { System.out.println(i + ": " + letters.get(i)); } prints 0: x, 1: y, 2: z.