Junior — Middle
What methods are used to traverse elements within data collections?
sobes.tech AI
Answer from AI
In Java, several main methods are used to traverse collection elements:
- For-each loop (enhanced for):
for (Element e : collection) {
// process e
}
- Iterator:
Iterator<Element> it = collection.iterator();
while (it.hasNext()) {
Element e = it.next();
// process e
}
- Streams API:
collection.stream().forEach(e -> {
// process e
});
- Classic for loop — applicable to lists with indices:
for (int i = 0; i < list.size(); i++) {
Element e = list.get(i);
// process e
}
The choice of method depends on the type of collection and the task. Iterator allows safe removal of elements during traversal, streams are convenient for functional style and parallel processing.