Java Collection Iteration Guide
In Java, there are various ways to iterate through elements in a collection, with the most common methods being to use an iterator or an enhanced for loop.
- Traversing a collection with an iterator:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
- Iterate through a collection using an enhanced for loop.
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
for(String element : list) {
System.out.println(element);
}
In addition to List, collection classes like Set and Map can also be traversed using similar methods. It is important to note that when using enhanced for loop, only the values of the elements can be accessed, and not the indexes. If you need to access the indexes of the elements, you can use the traditional for loop combined with the get method to traverse the collection.