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

  1. For-each loop (enhanced for):
for (Element e : collection) {
    // process e
}
  1. Iterator:
Iterator<Element> it = collection.iterator();
while (it.hasNext()) {
    Element e = it.next();
    // process e
}
  1. Streams API:
collection.stream().forEach(e -> {
    // process e
});
  1. 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.

What methods are used to traverse elements within… - sobes.tech