πŸ” Java How-To Examples
Estimated reading: 3 minutes 24 views

πŸ” Java ArrayList Loop – Different Ways to Iterate with Examples

🧲 Introduction

Looping through an ArrayList is one of the most common operations in Java. Whether you’re displaying items, applying calculations, or filtering data, understanding different looping methods is essential.

In this guide, you’ll learn how to:

  • βœ… Loop through an ArrayList using multiple approaches
  • βœ… Understand the advantages of each method
  • βœ… Apply clean and readable code practices

πŸ“˜ Sample ArrayList

Before we dive into looping techniques, let’s create a sample ArrayList:

import java.util.ArrayList;

public class LoopArrayList {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Grapes");
    }
}

βœ… We’ll use this fruits list in all the looping examples below.


πŸ” 1. For Loop (Index Based)

for (int i = 0; i < fruits.size(); i++) {
    System.out.println(fruits.get(i));
}

βœ… Explanation:

  • fruits.size() gives the total number of elements.
  • fruits.get(i) retrieves each element by index.

πŸ’‘ Use when you need the index during iteration.


πŸ”„ 2. Enhanced For Loop (For-Each)

for (String fruit : fruits) {
    System.out.println(fruit);
}

βœ… Explanation:

  • Clean and readable syntax.
  • Automatically fetches each element.

πŸ’‘ Best for readability and when index is not needed.


πŸ”ƒ 3. While Loop with Iterator

import java.util.Iterator;

Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

βœ… Explanation:

  • hasNext() checks if more elements exist.
  • next() retrieves the next element.

⚠️ Use this when modifying the list during iteration (like removing elements).


πŸš€ 4. Java 8 forEach + Lambda

fruits.forEach(fruit -> System.out.println(fruit));

βœ… Explanation:

  • Uses forEach() from Java 8 with a lambda.
  • Very concise and modern.

πŸ’‘ Great for clean, functional-style programming.


πŸ§ͺ 5. Using ListIterator (Bidirectional Traversal)

import java.util.ListIterator;

ListIterator<String> listIterator = fruits.listIterator();
while (listIterator.hasNext()) {
    System.out.println(listIterator.next());
}

βœ… Explanation:

  • ListIterator supports forward and backward movement.
  • Can be used to edit elements while iterating.

πŸ“‹ Comparison Table

Loop TypeSupports Index?Removes Elements Safely?Java Version
For Loopβœ… Yes⚠️ NoAll
Enhanced For Loop❌ No⚠️ NoJava 5+
While with Iterator❌ Noβœ… YesJava 2+
forEach + Lambda❌ No⚠️ NoJava 8+
ListIteratorβœ… Yes (both ways)βœ… YesJava 2+

πŸ“Œ Summary

In this article, you explored:

  • βœ… Five ways to loop over a Java ArrayList
  • βœ… When to use each method effectively
  • βœ… Tips for safe iteration and clean code

Mastering these looping techniques will help you write efficient and clean Java code when working with collections.


❓FAQ – Java ArrayList Looping

❓Which is the best loop for performance?

The traditional for loop is generally fastest for primitive types, but for objects like ArrayList, differences are negligible unless working with very large datasets.

❓Can I remove items during a loop?

Use Iterator or ListIterator to safely remove items during iteration.

❓Is Java 8 forEach better than loops?

Yes, for readability and functional programming style, but not ideal if you need to break or continue inside the loop.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

ArrayList Loop

Or Copy Link

CONTENTS
Scroll to Top