Keywords: Java | foreach | ArrayList | custom object | enhanced for loop
Abstract: This article explains how to use the enhanced for loop in Java to iterate over an ArrayList of custom objects, with examples and alternative methods like Java 8 streams.
Introduction
In Java development, working with collections of custom objects is frequent. A common requirement is to iterate over an ArrayList of user-defined classes, such as a Room object.
Enhanced For Loop Syntax
The enhanced for loop, introduced in Java 5, simplifies iteration. For a list of custom objects, the syntax is for (Type variable : collection) { ... }.
For example, with an ArrayList<Room>:
for (Room room : rooms) {
System.out.println(room.getName());
}
Detailed Code Example
Define a simple Room class:
public class Room {
private String name;
private int size;
// getters and setters
}
Then, iterate:
ArrayList<Room> rooms = new ArrayList<>();
// Assume rooms are added
for (Room room : rooms) {
if (room.getSize() > 100) {
System.out.println("Large room: " + room.getName());
}
}
Other Iteration Techniques
Alternative methods include using an Iterator or Java 8's forEach with streams.
With Iterator:
for (Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
Room room = i.next();
// process room
}
With Java 8 forEach:
rooms.forEach(room -> System.out.println(room.getName()));
Or with method reference:
rooms.forEach(System.out::println);
Conclusion
The enhanced for loop is the most straightforward way to iterate custom object lists in Java. For more advanced operations, Java 8 streams offer functional programming capabilities.