Sobes.tech
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:

  1. Enhanced for loop (for-each loop):
for (Element e : collection) {
    // process e
}
  1. Iterator:
Iterator<Element> iterator = collection.iterator();
while (iterator.hasNext()) {
    Element e = iterator.next();
    // process e
}
  1. Classic for loop (for lists with indices):
for (int i = 0; i < list.size(); i++) {
    Element e = list.get(i);
    // process e
}
  1. Stream API (since Java 8):
collection.stream().forEach(e -> {
    // process e
});
  1. forEach method of collections (Java 8+):
collection.forEach(e -> {
    // process e
});

The choice of method depends on the task and the type of collection.

In what ways can you iterate over elements of a… - sobes.tech