Friday, April 14, 2023

How to traverse iterate or loop ArrayList in Java

How to Loop ArrayList in Java
Iterating, traversing or Looping ArrayList in Java means accessing every object stored in ArrayList and performing some operations like printing them. There are many ways to iterate, traverse or Loop ArrayList in Java e.g. advanced for loop, traditional for loop with size(), By using Iterator and ListIterator along with while loop etc. All the method of Looping List in Java also applicable to ArrayList because ArrayList is an essentially List. In next section we will see a code example of Looping ArrayList in Java.



Loop ArrayList in Java – Code Example
How to loop iteratre or traverse ArrayList in JavaNow we know that there are multiple ways to traverse, iterate or loop ArrayList in Java, let’s see some concrete code example to know exactly How to loop ArrayList in Java. I prefer advanced for loop added in Java 1.5 along with Autoboxing, Java Enum, Generics, Varargs and static import, also known as foreach loop if I have to just iterate over Array List in Java. If I have to remove elements while iterating than using Iterator or ListIterator is the best solution.



import java.util.ArrayList;
import java.util.Iterator;

/**
 * Java program which shows How to loop over ArrayList in Java using advanced for loop,
 * traditional for loop and How to iterate ArrayList using Iterator in Java
 * advantage of using Iterator for traversing ArrayList is that you can remove
 * elements from Iterator while iterating.

 * @author
 */

public class ArrayListLoopExample {

 
    public static void main(String args[]) {
 
        //Creating ArrayList to demonstrate How to loop and iterate over ArrayList
        ArrayList<String> games = new ArrayList<String>(10);
        games.add("Cricket");
        games.add("Soccer");
        games.add("Hockey");
        games.add("Chess");
     
        System.out.println("original Size of ArrayList : " + games.size());
     
        //Looping over ArrayList in Java using advanced for loop
        System.out.println("Looping over ArrayList in Java using advanced for loop");
        for(String game: games){
            //print each element from ArrayList
            System.out.println(game);
        }
     
        //You can also Loop over ArrayList using traditional for loop
        System.out.println("Looping ArrayList in Java using simple for loop");
        for(int i =0; i<games.size(); i++){
            String game = games.get(i);
        }
     
        //Iterating over ArrayList in Java
        Iterator<String> itr = games.iterator();
        System.out.println("Iterating  over ArrayList in Java using Iterator");
        while(itr.hasNext()){
            System.out.println("removing " + itr.next() + " from ArrayList in Java");
            itr.remove();
        }
     
         System.out.println("final Size of ArrayList : " + games.size());
   
    }

}

Output:
original Size of ArrayList : 4
Looping over ArrayList in Java using advanced for loop
Cricket
Soccer
Hockey
Chess
Looping ArrayList in Java using simple for loop
Iterating  over ArrayList in Java using Iterator
removing Cricket from ArrayList in Java
removing Soccer from ArrayList in Java
removing Hockey from ArrayList in Java
removing Chess from ArrayList in Java
final Size of ArrayList : 0


That's all on How to iterate, traverse or loop ArrayList in Java. In summary use advance for loop to loop over ArrayList in Java, its short, clean and fast but if you need to remove elements while looping use Iterator to avoid ConcurrentModificationException.

Related Java Collection tutorials from this blog

6 comments:

  1. I have asked one question related to looping ArrayList, Interviewer said, is there any difference when you iterate over ArrayList by using foreach loop and by explicitly using Iterator? I don't see his point of asking this question, so I said, both should be Ok. Let me know, if there is real difference between both approaches.

    ReplyDelete
  2. What is the best way to iterate through ArrayList in Java?

    ReplyDelete
    Replies
    1. Best way to iterate through ArrayList is via ListIterator because it allows you to add element between current and next element using add() method, replace current element using set() method and remove current element using remove() method. It is also safe, because it can throw ConcurrentModificationException if ArrayList is modified after iterator begins.

      Delete
  3. Will it not throw concurrent modification exception because you are trying to remove the element while iterating through the Arraylist.

    ReplyDelete
    Replies
    1. No, because we are using Iterator.remove() method, it will throw concurrent modification exception only if you use ArrayList remove() method. You can try that yourself.

      Delete

Feel free to comment, ask questions if you have any doubt.