Thursday, September 14, 2023

4 Ways to Loop or Iterate over ArrayList in Java? Iterator, ListItreator, for loop and Enhanced foreach Example

Looping 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 here in detail. We are going to see examples of all three approaches in this ArrayList tutorial and find out which one is clean and the best method of looping ArrayList in Java. 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.

Update: 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 teh 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. 

How to Loop, Iterate or traverse Arraylist in Java - Code Example

 Essentially there are four 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.



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

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.

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





2. Iterating ArrayList in Java using Iterator and while loop

ArrayList Loop Example JavaAnother 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. 

Also by using Iterator approach for looping ArrayList you can remove element from ArrayList without fear of ConcurrentModificationException. See below for full code example of looping 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


That’s all on four examples to loop ArrayList in Java. We have seen foreach loop, Iterator, 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.


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 :

Anonymous said...

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.

Anonymous said...

@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 ?

Soya said...

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.

Gauri said...

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?

Saroj Saini said...

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

Cook said...

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.

JD said...

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

ravi said...

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

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

javin paul said...

@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.

Anonymous said...

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

Post a Comment