Search⌘ K
AI Features

Iterating Through Collections

Explore various strategies to iterate through Java collections like List, Set, and Map. Understand how to use enhanced for loops, Iterators, ListIterators, and the forEach method effectively. Learn when to safely remove elements during iteration and how to handle key-value pairs in Maps, enabling you to write clean, readable, and efficient code.

We have learned how to store data in collections like ArrayList, HashSet, and HashMap. However, data storage is only useful if we can efficiently access and process that data. Whether we are calculating the total price of a shopping cart, filtering a list of active users, or searching for a specific configuration setting, iteration is the mechanism that powers these operations. While traditional loops with integer indices work for lists, they often fail or become clumsy with sets and maps.

In this lesson, we will master the standard tools Java provides to walk through data structures cleanly, safely, and efficiently.

The enhanced for loop and the Iterable interface

A common and readable way to iterate over a collection in Java is the enhanced for loop (also known as the for each loop). It simplifies iteration when you don’t need the index, since you don’t have to manage a counter or check loop bounds manually.

It works with any class that implements the Iterable interface, which includes all standard collection types like List, Set, and Queue (but not Map directly).

Java 25
import java.util.List;
import java.util.ArrayList;
public class ForEachLoop {
public static void main(String[] args) {
List<String> servers = new ArrayList<>();
servers.add("Server-US-East");
servers.add("Server-EU-West");
servers.add("Server-Asia-Pacific");
// The enhanced for-loop
for (String server : servers) {
System.out.println("Checking status: " + server);
}
}
}
  • Line 12: We declare a loop variable server of type String. In each iteration, this variable holds the next element from the servers collection.

  • Line 13: We use the variable server directly. We do not need to manage an index i or call get(i).

This approach is excellent for reading data. However, it has a limitation: it hides the underlying iterator mechanism. Consequently, we cannot easily modify the collection (like removing the current item) or access the index of the ...