DEV Community

Raghwendra Sonu
Raghwendra Sonu

Posted on

Different ways of iterating an ArrayList ?

In Java, there are several ways to iterate over an ArrayList, which is a dynamic array implementation provided by the Java Collections Framework. Here are some common ways to iterate through an ArrayList:

Using a Traditional For Loop:

ArrayList list = new ArrayList<>();
// Add elements to the list
for (int i = 0; i < list.size(); i++) {
String element = list.get(i);
// Process the element
}

Using an Enhanced For Loop (for-each loop):

ArrayList list = new ArrayList<>();
// Add elements to the list
for (String element : list) {
// Process the element
}

Using Iterator:

ArrayList list = new ArrayList<>();
// Add elements to the list
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
// Process the element
}

Using forEach() with Lambda Expression (Java 8 onwards):

ArrayList list = new ArrayList<>();
// Add elements to the list
list.forEach(element -> {
// Process the element
});

Using forEach() with Method Reference (Java 8 onwards):

ArrayList list = new ArrayList<>();
// Add elements to the list
list.forEach(System.out::println); // Example of printing elements

Using Streams (Java 8 onwards):

ArrayList list = new ArrayList<>();
// Add elements to the list
list.stream().forEach(element -> {
// Process the element
});

Using ListIterator (for iterating in both directions):

ArrayList list = new ArrayList<>();
// Add elements to the list
ListIterator listIterator = list.listIterator();
while (listIterator.hasNext()) {
String element = listIterator.next();
// Process the element
}

Each of these methods has its advantages and use cases. The enhanced for loop and iterator are common and widely used. The introduction of streams and lambda expressions in Java 8 provides a more concise and expressive way to iterate over collections. Choose the method that best fits your specific requirements and coding style.

Top comments (0)