Back to Java
2026-01-256 min read

ArrayList Loop

Learn ArrayList Loop step by step with clear examples and exercises.

Why This Matters

In Java programming, understanding how to loop through an ArrayList is essential for every developer. Looping allows you to iterate over collections efficiently and perform various operations such as searching, sorting, or modifying elements in the list. Mastering ArrayList loops will improve your coding efficiency, help you solve real-world programming problems, and avoid common bugs that may arise during development.

Prerequisites

Before diving into looping through an ArrayList, it is crucial to have a good understanding of the following concepts:

  1. Basic Java syntax: variables, data types, operators, control structures (if-else statements, loops)
  2. Object-oriented programming principles in Java: classes, objects, methods, inheritance, and polymorphism
  3. Understanding of collections in Java: ArrayList, LinkedList, HashSet, etc., and their basic operations like add(), remove(), size(), get()
  4. Familiarity with exception handling (e.g., NullPointerException, UnsupportedOperationException)
  5. Understanding of the differences between arrays and collections in Java

Core Concept

Looping through an ArrayList

To loop through an ArrayList in Java, we can use either a for-each loop or a traditional for loop. Here's how to do it with both methods:

For-each loop (recommended)

ArrayList<Integer> numbers = new ArrayList<>(); // create an ArrayList of Integers
numbers.add(1);
numbers.add(2);
numbers.add(3);

for (int number : numbers) {
System.out.println(number); // print each element in the ArrayList
}

Traditional for loop

ArrayList<Integer> numbers = new ArrayList<>(); // create an ArrayList of Integers
numbers.add(1);
numbers.add(2);
numbers.add(3);

for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i)); // print each element in the ArrayList using its index
}

Iterator

Another way to loop through an ArrayList is by using an Iterator. This method allows more control over the iteration process and can be useful when dealing with specific scenarios, such as removing elements during iteration:

ArrayList<Integer> numbers = new ArrayList<>(); // create an ArrayList of Integers
numbers.add(1);
numbers.add(2);
numbers.add(3);

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next()); // print each element in the ArrayList using an Iterator
}

Looping through an ArrayList with custom operations

In addition to printing elements, you can also perform custom operations on each element during iteration:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);

// Loop through the ArrayList and double each element
for (int i = 0; i < numbers.size(); i++) {
numbers.set(i, numbers.get(i) * 2); // replace each element with its doubled value
}

System.out.println(numbers); // [2, 4, 6, 8, 10]

Looping through an ArrayList with custom conditions

You can also loop through an ArrayList using custom conditions:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);

for (int number : numbers) {
if (number % 2 == 0) { // only print even numbers
System.out.println(number);
}
}

Worked Example

Let's take a look at a practical example of looping through an ArrayList and performing an operation on each element:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);

// Loop through the ArrayList and double each even number
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) % 2 == 0) { // check if the current number is even
numbers.set(i, numbers.get(i) * 2); // replace the even number with its doubled value
}
}

System.out.println(numbers); // [1, 4, 3, 8, 5]

Common Mistakes

  1. Forgetting to initialize the ArrayList:
ArrayList<Integer> numbers = null; // incorrect initialization
  1. Accessing an index out of bounds:
for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i + 1)); // accessing the element at index i+1, which is out of bounds
}
  1. Using a for-each loop with an ArrayList that contains null values:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(null); // add a null value to the ArrayList

// This will cause a NullPointerException when trying to print each element
for (int number : numbers) {
System.out.println(number);
}
  1. Trying to modify an ArrayList during iteration with a for-each loop:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// This will cause an UnsupportedOperationException when trying to add a new element during iteration
for (int number : numbers) {
numbers.add(4); // adding a new element during iteration
}
  1. Iterating through an ArrayList with an outdated iterator:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next(); // get the next element
// perform some operation on number...

// If you modify the ArrayList during iteration, it's important to call iterator.remove() or update the iterator
if (number > 2) {
numbers.remove(number); // remove the current element from the ArrayList
}
}

Practice Questions

  1. Write a Java program that loops through an ArrayList of Strings and counts the number of vowels in each string.
  2. Given an ArrayList of Integers, write a function that finds the second-highest number in the list.
  3. Write a program that reads user input as an ArrayList of Integers and sorts it using a custom comparator that considers only even numbers.
  4. Write a Java program that loops through an ArrayList of Strings and counts the occurrence of each word in the list.
  5. Given an ArrayList of Integers, write a function that finds the kth smallest number in the list (k is a user-defined integer).
  6. Write a program that loops through an ArrayList of Strings and removes all duplicate words, maintaining the order of the unique words.
  7. Write a Java program that loops through an ArrayList of custom objects (e.g., Person with properties like name, age) and calculates the average age of the people in the list.
  8. Given an ArrayList of Integers, write a function that finds all pairs of numbers whose sum equals a given target number.
  9. Write a Java program that loops through an ArrayList of custom objects (e.g., Shape with properties like type and area) and calculates the total area of all shapes in the list.
  10. Write a program that loops through an ArrayList of custom objects (e.g., Employee with properties like name, salary, department) and sorts them first by salary, then by name within each salary group.

FAQ

  1. Why can't I use a for loop to iterate through an ArrayList like I would with arrays?
  • Java's ArrayList is not an array, but rather a dynamic collection of objects (in this case, the Object class). The for-each loop provides a more convenient and efficient way to iterate over collections.
  1. Can I use a traditional for loop to remove elements from an ArrayList during iteration?
  • Yes, but it's generally not recommended because it can lead to ConcurrentModificationException. Using an Iterator or the removeIf() method is safer and more efficient in such cases.
  1. What happens if I try to add an element to an ArrayList while iterating through it with a for-each loop?
  • Adding elements during iteration using a for-each loop will cause an UnsupportedOperationException. To avoid this, use the add() method on the ArrayList object before or after the iteration.
  1. Why does my ArrayList iterator stop working after removing some elements?
  • When you remove elements from an ArrayList during iteration using an Iterator, the iterator becomes outdated. To fix this, call iterator.remove() or create a new iterator after each removal.
  1. Is it possible to loop through an ArrayList in reverse order?
  • Yes, you can loop through an ArrayList in reverse order by iterating from the end of the list (using numbers.size() - 1) and decrementing the index during iteration. Alternatively, use the Collections.reverse() method to reverse the order of the ArrayList before iteration.
  1. Why does my ArrayList iterator throw a NoSuchElementException when I try to get the next element?
  • This exception occurs when there are no more elements left in the ArrayList. To avoid this, check if iterator.hasNext() returns true before calling iterator.next().
ArrayList Loop | Java | XQA Learn