On this section we will be showing some java examples on how to iterate or loop through an arraylist. This is one of the most important knowledge in dealing with list and arrays on how to loop for each elements. Why would be needing to loop through the elements of an arraylist? Well, to make it simple it is for the intention of accessing each member of the the list. Either we would be using the elements to do some complicated logical program or simply just to print it.
Background of ArrayList
From official java documentation the following best describes an ArrayList:
- Resizable-array implementation of the List interface.
- Implements all optional list operations
- permits all elements including null
- In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list
Ways to loop through an ArrayList
There are several ways of iterating through the elements, below are some of it
- ArrayList iteration through for loop
- Using while loop
- Using do while loop in interation
- And the advance for loop
Java Examples in looping through an ArrayList
The following are comprehensive examples in dealing with ArrayList
Loop through an ArrayList using for statement
Basically on this example we declared an ArrayList of fruits and then we just iterate through the elements using for loop. After which we just prints out those elements. Its worthwhile that you might need to take a look on how we have used the add method, size of ArrayList and how we have used Generics ArrayList<String>.
package com.javatutorialhq.java.examples; import java.util.ArrayList; /* * This example source code on how to deal * with ArrayList using for loop */ public class ForLoopArrayList { public static void main(String[] args) { // initialize our ArrayList ArrayList<String> listFruits = new ArrayList<String>(); // put contents on our list listFruits.add("pineapple"); listFruits.add("apple"); listFruits.add("mango"); // iterate through our list for(int i=0;i<listFruits.size();i++){ // print member of our arraylist one by one System.out.println(listFruits.get(i)); } } }
Sample Output
Running the above code we will be having the following result
Loop through an ArrayList using while statement
On this example, we basically just iterate through a List of Integer using while loop and then print each individual elements.
package com.javatutorialhq.java.examples; import java.util.ArrayList; /* * This example source code on how to deal * with ArrayList using while loop */ public class WhileLoopArrayList { public static void main(String[] args) { // initialize our ArrayList ArrayList<Integer> listNumbers = new ArrayList<Integer>(); // put contents on our list listNumbers.add(7145); listNumbers.add(487); listNumbers.add(-1032); listNumbers.add(454); // iterate through our list int index = 0; int maxIndex = listNumbers.size(); while (index < maxIndex) { // print member of our arraylist one by one System.out.println(listNumbers.get(index)); index++; } } }
In dealing with while loop, it’s a little bit harder than the for loop because small mistake like for example the condition
while (index < maxIndex)
if we have put the index <= maxIndex, the output would throw an ArrayIndexOutOfBounds exception. But it doesn’t mean that you could not use the index <=maxIndex, its just a matter of adjustment. see below for a sample snippet that would work for this condition
int index = 1; int maxIndex = listNumbers.size(); while (index <= maxIndex) { // print member of our arraylist one by one System.out.println(listNumbers.get(index-1)); index++; }
To compensate for our modified condition, we have started the index to 1 instead of 0. However in order to get the first index we have used get(index -1) because remember that for ArrayList the index starts at 0.
Sample Output
Running the above code we will be having the following result
Loop through an ArrayList using do while statement
On this example, we basically just iterate through a List of String using do while loop and then print each individual elements. This is similar to while loop but on this case we will print first the element before iteration. Dealing with this loop is a little bit tricky which we will be showing in later discussion. First lets go through first with this example:
package com.javatutorialhq.java.examples; import java.util.ArrayList; /* * This example source code on how to deal * with ArrayList using do while loop */ public class DoWhileLoopArrayList { public static void main(String[] args) { // initialize our ArrayList ArrayList<String> countries = new ArrayList<String>(); // put contents on our list countries.add("singapore"); countries.add("Thailand"); countries.add("Russia"); countries.add("New Zealand"); countries.add("Canada"); // declare lower and upper bounds of our iteration element int index = 0; int maxIndex = countries.size(); // iterate through our list do{ // print each element System.out.println(countries.get(index)); index++; } while(index < maxIndex); } }
Running the above example we will be having the following output.
You would have noticed how the printing of elements comes first before the increment of the index. If you put the increment before printing, IndexOutOfBoundsException will be thrown. Why? because if we interchange the print and index iteration, the index would start at 1. Remember that the first element is 0. Thus if we start at 1, we would be accessing an element of a List that does not exist. Be careful in dealing with loops. It takes a lot of practice in order to get this right and avoid the horrible IndexOutOfBoundsException, which I believe you would be getting a lot in the beginning of your programming experience.
Using advance for loop
Now my favorite looping mechanism the advance for loop or sometimes called enhance for loop but techincally being called for each loop. This is easy to use and no need to worry on indexes, we just iterate through the elements. Now here is a concrete example on which looping strategy is much better.
package com.javatutorialhq.java.examples; import java.util.ArrayList; /* * This example source code on how to deal * with ArrayList using advance for loop */ public class AdvanceForLoopArrayList { public static void main(String[] args) { // initialize our ArrayList ArrayList<String> profession = new ArrayList<String>(); // put contents on our list profession.add("singapore"); profession.add("Thailand"); profession.add("Russia"); profession.add("New Zealand"); profession.add("Canada"); // loop through the arrayList for(String s:profession){ // print each element System.out.println(s); } } }
Running the above example code we will be having the following output on our console:
Conclusion:
There are multiple ways in looping through an arraylist. We have provided 4 ways however as we have gone through the examples, we have shown also some possible modifications on our codes and that would give more complications in handling ArrayList loops. On the last part we have show the for-each loop which is easy to use. However if we are dealing with index i would suggest other methods because they are more versatile.
In short, there is no best method here and the choice would be at the hands of the programmer. As long as we handle properly the IndexOutOfBoundsException which will definitely makes every programmer crazy, we are on the right track.
Based on my personal preference i am using for loop and the enhance for loop depending on the requirements. In order to master these looping methods, I would suggest do more practice. If you gain years of experience, understanding these would be a piece of cake.