5 Ways to Loop or Iterate over ArrayList in Java? (original) (raw)
Looping over an ArrayList in Java or Iteration over ArrayListis 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.
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:
Looping using Java 5 foreach loop.
Looping ArrayList using for loop and size() method.
Iterating ArrayList using Iterator.
Traversing ArrayList using ListIterator in Java.
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.
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:
How to Iterate over an ArrayList in Java?
See 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:
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.