Sub topic 5
Looping Over Collections
You will often want to do something with every element in a collection. You might print each name, add up numbers, or look for a match. Going through the elements one at a time is called iteration. Java gives you a few ways to do it.
The for-each loop
A for-each loop is a loop that hands you each element in turn, without you having to count. You read it as "for each String name in names."
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
}
}The type before the colon (String) must match the element type of the collection. The for-each loop works on any Collection, including lists and sets. It also works on plain arrays.
The indexed for loop
A List has positions, so you can also loop by index. An index is the position number of an element, starting at 0.
import java.util.List;
public class IndexLoopDemo {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Ben", "Cara");
for (int i = 0; i < names.size(); i++) {
System.out.println(i + ": " + names.get(i));
}
// 0: Ana
// 1: Ben
// 2: Cara
}
}Use this style when you need the position number. A Set has no index, so this style does not work on a set.
The Iterator
An Iterator is an object that walks through a collection one step at a time. The for-each loop uses one behind the scenes. You can also use an iterator yourself. It has two main methods:
hasNext()returnstrueif there is another element.next()returns that element and moves forward.
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class IteratorDemo {
public static void main(String[] args) {
Set<String> colors = new HashSet<>(Set.of("red", "green", "blue"));
Iterator<String> it = colors.iterator();
while (it.hasNext()) {
String color = it.next();
System.out.println(color);
}
}
}The order of the colors printed here may differ from the order you wrote them in. A HashSet makes no promise about order. A later chapter covers sets that do keep an order.
Which loop should you use?
| Loop | Works on | Use it when |
|---|---|---|
| for-each | Any collection or array | You just need each element |
| Indexed for | Lists and arrays | You need the position number |
| Iterator | Any collection | You need to remove elements while looping |
Exercise
You have a List<Integer> called scores holding 70, 85, and 90. Write a for-each loop that adds up all the scores into a variable called total.
Show answer
int total = 0; for (int s : scores) { total += s; } After the loop, total is 245. Java unboxes each Integer to an int automatically.
Exercise
Why can't you use an indexed for loop with names.get(i) on a HashSet?
Show answer
A Set has no positions, so it has no get(int) method. Use a for-each loop or an Iterator instead.