Junior — Middle
In what ways can you iterate over elements of a collection in programming?
sobes.tech AI
Answer from AI
In Java, there are several ways to iterate over collection elements:
- Enhanced for loop (for-each loop):
for (Element e : collection) {
// process e
}
- Iterator:
Iterator<Element> iterator = collection.iterator();
while (iterator.hasNext()) {
Element e = iterator.next();
// process e
}
- Classic for loop (for lists with indices):
for (int i = 0; i < list.size(); i++) {
Element e = list.get(i);
// process e
}
- Stream API (since Java 8):
collection.stream().forEach(e -> {
// process e
});
- forEach method of collections (Java 8+):
collection.forEach(e -> {
// process e
});
The choice of method depends on the task and the type of collection.