Iterating over an ArrayList in Java

author : Sai K

An ArrayList is a resizable array implementation of the List interface. This guide will provide examples of how to

iterate over an ArrayList using different methods, including detailed explanations and outputs. Additionally, it will

cover how to iterate over an ArrayList containing custom objects.

Table of Contents

  • Introduction

  • Using For-Loop

  • Using Enhanced For-Loop

  • Using Iterator

  • Using ListIterator

  • Using forEach Method (Java 8)

  • Using Stream API (Java 8)

  • Iterating Over an ArrayList with Custom Objects

  • Conclusion
  • 1. Introduction

    An ArrayList is a part of the Java Collections Framework and is an implementation of the List interface that

    provides resizable array functionality. It is useful for scenarios where you need a dynamic array

    2. Using For-Loop

    The traditional for-loop is a basic and flexible way to iterate over an ArrayList.

    Example: Using For-Loop

    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ForLoopExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            for (int i = 0; i < fruits.size(); i++) {
                System.out.println(fruits.get(i));
            }
        }
    }

    Output:

    
                        Apple
                        Banana
                        Orange
                    

    3. Using Enhanced For-Loop

    The enhanced for-loop (or for-each loop) provides a simpler and more readable way to iterate over an ArrayList.

    Example: Using Enhanced For-Loop

    
    import java.util.ArrayList;
    import java.util.List;
    
    public class EnhancedForLoopExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            for (String fruit : fruits) {
                System.out.println(fruit);
            }
        }
    }
                    

    Output:

    
                        Apple
                        Banana
                        Orange
                    

    4. Using Iterator

    The Iterator provides a way to iterate over the elements and allows element removal during iteration if needed.

    Example: Using Iterator

    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class IteratorExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            Iterator iterator = fruits.iterator();
            while (iterator.hasNext()) {
                String fruit = iterator.next();
                System.out.println(fruit);
            }
        }
    }
                   

    Output:

    
                    Apple
                   Banana
                   Orange
                   

    5. Using ListIterator

    The ListIterator provides additional functionality compared to the Iterator, such as bidirectional traversal and

    modification of elements.

    Example: Using ListIterator

    
        import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;
    
    public class ListIteratorExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            ListIterator listIterator = fruits.listIterator();
            while (listIterator.hasNext()) {
                String fruit = listIterator.next();
                System.out.println(fruit);
            }
    
            System.out.println("Reverse Iteration:");
            while (listIterator.hasPrevious()) {
                String fruit = listIterator.previous();
                System.out.println(fruit);
            }
        }
    }
    

    Output:

    
    Apple
    Banana
    Orange
    Reverse Iteration:
    Orange
    Banana
    Apple
    

    6. Using forEach Method (Java 8)

    The forEach method is part of the Java 8 Stream API and provides a functional approach to iteration.

    Example: Using forEach Method

    
        import java.util.ArrayList;
    import java.util.List;
    
    public class ForEachMethodExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            // Using forEach with lambda expression
            fruits.forEach(fruit -> System.out.println(fruit));
    
            // Using forEach with method reference
            fruits.forEach(System.out::println);
        }
    }
    

    Output:

    
    Apple
    Banana
    Orange
    

    7. Using Stream API (Java 8)

    The Stream API provides a powerful way to process sequences of elements, including iteration.

    Example: Using Stream API

    
        import java.util.ArrayList;
    import java.util.List;
    
    public class StreamAPIExample {
        public static void main(String[] args) {
            List fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Orange");
    
            // Using stream and forEach
            fruits.stream().forEach(fruit -> System.out.println(fruit));
    
            // Using parallel stream and forEach
            fruits.parallelStream().forEach(fruit -> System.out.println("Parallel: " + fruit));
        }
    }
    

    Output:

    
    Apple
    Banana
    Orange
    Parallel: Apple
    Parallel: Banana
    Parallel: Orange
    

    8. Iterating Over an ArrayList with Custom Objects

    When dealing with custom objects in an ArrayList, you can iterate over the list similarly to how you would with

    built-in types. Here is an example using a custom Person class.

    Custom Object Example: Using Enhanced For-Loop

    
        import java.util.ArrayList;
    import java.util.List;
    
    class Person {
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
        @Override
        public String toString() {
            return "Person{name='" + name + "', age=" + age + '}';
        }
    }
    
    public class CustomObjectExample {
        public static void main(String[] args) {
            List persons = new ArrayList<>();
            persons.add(new Person("Alice", 30));
            persons.add(new Person("Bob", 25));
            persons.add(new Person("Charlie", 35));
    
            // Using Enhanced For-Loop
            System.out.println("Using Enhanced For-Loop:");
            for (Person person : persons) {
                System.out.println(person);
            }
    
            // Using Iterator
            System.out.println("\nUsing Iterator:");
            Iterator iterator = persons.iterator();
            while (iterator.hasNext()) {
                Person person = iterator.next();
                System.out.println(person);
            }
    
            // Using forEach Method (Java 8)
            System.out.println("\nUsing forEach Method (Java 8):");
            persons.forEach(person -> System.out.println(person));
    
            // Using Stream API (Java 8)
            System.out.println("\nUsing Stream API (Java 8):");
            persons.stream().forEach(person -> System.out.println(person));
        }
    }
    

    Output:

    
        Using Enhanced For-Loop:
    Person{name='Alice', age=30}
    Person{name='Bob', age=25}
    Person{name='Charlie', age=35}
    
    ```java
    Using Iterator:
    Person{name='Alice', age=30}
    Person{name='Bob', age=25}
    Person{name='Charlie', age=35}
    
    Using forEach Method (Java 8):
    Person{name='Alice', age=30}
    Person{name='Bob', age=25}
    Person{name='Charlie', age=35}
    
    Using Stream API (Java 8):
    Person{name='Alice', age=30}
    Person{name='Bob', age=25}
    Person{name='Charlie', age=35}
    

    9. Conclusion

    In this guide, we covered various methods to iterate over an ArrayList in Java:

    • Using For-Loop: Basic and flexible method.

    • Using Enhanced For-Loop: Simplifies code and improves readability.

    • Using Iterator: Allows element removal during iteration.

    • Using ListIterator: Supports bidirectional traversal and modification of elements.

    • Using forEach Method (Java 8): Provides a functional programming approach.

    • Using Stream API (Java 8): Offers powerful operations for processing sequences of elements, including parallel processing.

    Additionally, we demonstrated how to iterate over an ArrayList containing custom objects, ensuring proper

    handling and display of object attributes.

    By following the steps and examples provided, you should now be able to efficiently iterate over ArrayLists in

    your Java applications and choose the iteration method that best fits your needs.

    Related Java and Advanced Java Tutorials/Guides