Wednesday, July 24, 2024

5 Ways to Loop or Iterate over ArrayList in Java?

Looping over an ArrayList in Java or Iteration over ArrayList is very similar to a looping Map in Java. In order to loop ArrayList in Java, we can use either foreach loop, simple for loop, or Java Iterator from ArrayList. We have already touched iterating ArrayList in 10 Example of ArrayList in Java and we will see them here in more detail. We are going to see examples of all four approaches in this ArrayList tutorial and find out which one is clean and the best method of looping ArrayList in Java? But, before start writing an example for loop in ArrayList let's think about why do we need to iterate, traverse or loop an ArrayList if it’s based on the index and backed by Array.

If we know the index of elements then we can directly get that particular element from ArrayList but if you want to print all elements of ArrayList and do some operation one by one on each of them, only looping or traversing will help you.

This article is in continuation of my earlier tutorial on ArrayList like How to sort ArrayList in Java on descending order and How to convert Array ArrayList in Java. If you haven’t read them already then you may find them useful and interesting.

From Java 8 onwards you can also use functional programming and Stream.forEach() method to loop over an ArrayList in Java. You can first convert ArrayList to Stream and then call the forEach() method and pass is a Consumer interface implementation or Lambda expression like System.out.println()  which will print all elements on ArrayList one by one. 






What are 5 ways to Loop, Iterate or traverse ArrayList in Java? 

Here are the 5 ways to iterate, traverse of loop ArrayList in Java:
1) Looping using Java 5 foreach loop.
2) Looping ArrayList using for loop and size() method.
3) Iterating ArrayList using Iterator.
4) Traversing ArrayList using ListIterator in Java.
5) Using Stream.forEach() function for going over each element

Now, let's deep dive into each approach and find the pros and cons of each with sample code and examples:

1. Looping ArrayList with foreach loop on Java 5

We can iterate on Java ArrayList using foreach loop introduced in Java 5, by far most clean method until you don't need to remove elements from ArrayList in that case you must use Java Iterator for looping or iterating over ArrayList

This is a simple and safe method but doesn't provide access to the index which you can get while using the classical for loop method. 

Since ArrayList provides size() method you can also use plain old for(int i; i<size; i++) loop also for iterating or traversing ArrayList in Java. 

See the example section post for a complete code example of looping ArrayList in Java.

 for(String element: loopList){
   System.out.println(element);
 }

This loop doesn't have any counter and it will go through all the element of ArrayList one by one and print them. You can not just print but do whatever you want to do with the current element which is stored in the element object you declare in the loop. 



2. Iterating ArrayList in Java using Iterator and while loop

Another cool approach of looping ArrayList is using Iterator in combination of while loop and traverse until you get to the end of ArrayList. Iterator has a method hasNext() which will return true until there is an element in Iterator. 

Always call hasNext() before calling next() method on Iterator to avoid java.util.NoSuchElementException. 

Here is the code example:

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

Also by using Iterator approach for looping ArrayList you can remove element from ArrayList without fear of ConcurrentModificationException


3. Looping over ArrayList using for loop and size method

Here is another way to loop over an ArrayList in Java, in this method I have used classic for loop and size method to print each element of ArrayList 

for(int i=0; i<loopList.size(); i++){
  System.out.println(loopList.get(i));
}
This is similar to going through an array in Java. Instead of array you just have an ArrayList here. 

4. Iterating over ArrayList using ListIterator in Java (Bi-directional)

You can also use ListIterator to iterate over an ArrayList in Java. This approach is similar to Iterator but ListIterator also allow you to move in both direction as it provides both next() and prev() method 


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

You can also remove element from ArrayList while using ListIterator in Java. 


5. Looping over ArrayList using Stream.forEach() 

This is a relatively new and functional style of looping over an ArrayList or Collection in Java. The forEach() method is defined in Stream class and it accept a Consumer object, which is a functional interface. 

Consumer takes an object and return nothing, one example of this is System.out.println() which takes an object and just print to console, doesn't return anything.

Hence you can use this method to go through all element of ArrayList and print them. 

Here is a code example:

loopList.forEach(element -> {
 System.out.println(element);
});
This method allows you to use lambda expression and functional programming idioms. Also when you are working on Stream pipeline this is the method you should use. 

Here is also a nice diagram with sample code to show all the 5 ways of iterating over an ArrayList in Java for quick reference:


5 Ways to Loop or Iterate over ArrayList in Java?




How to Iterate over an ArrayList in Java?

ArrayList Loop Example JavaSee below for full code example of looping or iterating over ArrayList in Java.

package test;

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

public class ArrayListLoopExample {

    public static void main(String args[]){
     
        //Creating Arraylist for loop example
        ArrayList<String> loopList = new ArrayList<String>();
     
        //Storing elements in Java Arraylist
        loopList.add("low cost personal loan");
        loopList.add("cheap personal loan");
        loopList.add("personal loan in 24 hours");
     
        //Loop Arraylist using foreach loop of JDK1.5
        System.out.println("=====================================================");
        System.out.println("ArrayList Loop Example using foreach loop of JDK 1.5");
        for(String element: loopList){
            System.out.println(element);
        }
     
        //Loop Arraylist using simple for loop and size method
        System.out.println("=====================================================");
        System.out.println("ArrayList Loop Example using for loop and size()");
        for(int i=0; i<loopList.size(); i++){
            System.out.println(loopList.get(i));
        }
     
        //Iterate Arraylist using iterator and while loop in Java
        System.out.println("=====================================================");
        System.out.println("ArrayList Loop Example using Iterator and while loop");
        Iterator<String> iterator = loopList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
     
        //Iterate Arraylist using ListIterator and while loop in Java
        System.out.println("=====================================================");
        System.out.println("ArrayList Loop Example using ListIterator and while loop");
        ListIterator<String> listIterator = loopList.listIterator();
        while(listIterator.hasNext()){
            System.out.println(listIterator.next());
        }
    }
}

Output:
=====================================================
ArrayList Loop Example using foreach loop of JDK 1.5
low cost personal loan
cheap personal loan
personal loan in 24 hours
=====================================================
ArrayList Loop Example using for loop and size()
low cost personal loan
cheap personal loan
personal loan in 24 hours
=====================================================
ArrayList Loop Example using Iterator and while loop
low cost personal loan
cheap personal loan
personal loan in 24 hours
=====================================================
ArrayList Loop Example using ListIterator and while loop
low cost personal loan
cheap personal loan
personal loan in 24 hours



Also, here is a nice diagram which showing the top ways to iterate over an ArrayList in Java:

How to loop or Iterate over ArrayList in Java? Iterator, ListItreator, for loop and Enhanced foreach example


That’s all on five examples to loop or Iterate over an ArrayList in Java. We have seen foreach loop, Iterator, ListIterator, Stream.forEach(), and other approaches for traversing ArrayList and in my opinion foreach loop rules for simple iteration and Iterator rules if you need to remove elements from ArrayList during iteration. 

The ListIterator also offers to add() method to add new elements in ArrayList while looping and most importantly you can traverse on both direction. It also allow you to modify the List like adding or removing element. 


Other Java Collection tutorials you may like

Also, what is your favorite way to loop over ArrayList in Java? for loop, Iterator, ListIterator, enhanced for loop or JDK 8 Stream forEach() method? Let me know in comments. 

10 comments:

  1. With the size() approach I would rather write the code like this:

    int size = loopList.size();
    for(int i=0; i<size; i++){
    }

    This avoids repeated calls to size(). This could prove costly if the list has many records.

    ReplyDelete
  2. @Anonymous that doesn't matter, now days JVM and JRE are intelligent enough to optimize those. My question is looping through Iterator on ArrayList is faster than looping ArrayList via for loop ?

    ReplyDelete
  3. Best way to iterate over ArrayList is by using advanced for-each loop added in Java 5. I do see value of using Iterator or ListIterator for iterating over ArrayList but only if I want to remote elements from ArrayList during Iteration. for simple Iterate and read scenario for-each loop is much cleaner.

    ReplyDelete
  4. Hi Javin, What is the best way to iterate over ArrayList in Java e.g. using Iterator, ListIterator, for loop with index or Java 5 foreach loop?

    ReplyDelete
  5. Great post with good content .

    For-each loop limitations
    Three scenarios where you can not use for each loop

    for each loop provides a way to iterate over a collection of objects of class implementing Iterable interface. It provides little better performance as compared to traditional for loop and is a cleaner way to iterate over a collection. It removes the chances of error that could be introduced while iterating over multiple collection through traditional for loop . Developer could got wrong in updating and traversing over changing indexes of objects in collection . This kind of error is unlikely in for each loop

    But there are situations where for-each can't be used

    1. If you want to remove an element of collection while iterating for-each provides no remove method. So you can't use it in such scenario

    2. If you want to replace some element in collection while iterating over collection You can't do that as there is no replace or update method here neither you have control to access the element with its index value .

    3.A situation where you are working in parallel with multiple collections have to do a lot of operation with current index value of iterable collection. You don't have access to element index while iterating with for-each loop So you can't use it.

    Read here about - for-each loop limitations Three scenarios where you can not use for each loop

    http://efectivejava.blogspot.in/2013/07/for-each-loop-limitations.html

    ReplyDelete
  6. Hello guys, Which is the fastest way to loop AraryList in Java? I have to iterate through each object and only select few of them, which pass certain criterion. It's like filtering from functional programming, Though I am familiar with looping using foreach loop, I am not sure if that's the best way to approach my scenario. Any bit of wisdom, would be greatly appreciated.

    ReplyDelete
  7. for (Sting nombre: nombresList) {
    System.out.println("\nNombre #" + (nombresList.indexOf(nombre)+1));
    System.out.println(nombre);
    }

    ReplyDelete
  8. // We can use Enumeration as well for iteration.
    Enumeration s = Collections.enumeration(loopList);

    while (s.hasMoreElements()) {
    System.out.println(s.nextElement());
    }

    ReplyDelete
  9. @ravi, yes you can use enumeration but you should avoid using it because its a legacy class and may be removed in future releases. Iterator should be preferred over enumeration for traversing.

    ReplyDelete
  10. please tell me how i can loop an arraylist of objects?

    ReplyDelete