May 19, 2022

How to Iterate Java ArrayList

In this post we’ll see different ways to iterate an ArrayList in Java. Your options to iterate an ArrayList are as follows-

  1. Using normal for loop
  2. Using For-Each loop (Advanced for loop), available from Java 5
  3. Using Iterator or ListIterator (Use ListIterator only if you want to iterate both forward and backward rather than looping an ArrayList sequentially).
  4. Using forEach statement available from Java 8

Iterate an ArrayList in Java Example

Here is a Java example code that shows all of the above mentioned ways to loop an ArrayList.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class ArrayListIteration {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    System.out.println("**Iterating using normal for loop**");
    for(int i = 0; i < nameList.size(); i++){
      System.out.println("Name-- " + nameList.get(i));
    System.out.println("**Iterating using For-Each loop**");
    for(String name : nameList){
      System.out.println("Name- " + name);
    System.out.println("**Iterating using Iterator**");
    // getting iterator
    Iterator itr = nameList.iterator();
      System.out.println("Name- " +;
    System.out.println("**Iterating using ListIterator**");
    ListIterator ltr = nameList.listIterator();
      System.out.println("Name- " +;
    System.out.println("**Iterating using forEach statement**");
    nameList.forEach((n)->System.out.println("Name - " + n));
**Iterating using normal for loop**
Name-- Adam
Name-- Amy
Name-- Jim
Name-- Leo
**Iterating using For-Each loop**
Name- Adam
Name- Amy
Name- Jim
Name- Leo
**Iterating using Iterator**
Name- Adam
Name- Amy
Name- Jim
Name- Leo
**Iterating using ListIterator**
Name- Adam
Name- Amy
Name- Jim
Name- Leo
**Iterating using forEach statement**
Name - Adam
Name - Amy
Name - Jim
Name - Leo

So these are the options for iterating an ArrayList in Java. If you just want to loop through the list sequentially for-each loop is the best option. If you want to modify while iterating then Iterator or ListIterator should be used otherwise any Structural modification to the list will result in ConcurrentModificationException being thrown.

That's all for the topic How to Iterate Java ArrayList. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment