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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series