In this example, we will learn to iterate over the elements of an arraylist in Java.
Example 1: Iterate through ArrayList using for loop
import java.util.ArrayList; class Main { public static void main(String[] args) { // Creating an array list ArrayList<String> languages = new ArrayList<>(); languages.add("Java"); languages.add("JavaScript"); languages.add("Python"); System.out.println("ArrayList: " + languages); // Using for loop System.out.println("Iterating over ArrayList using for loop: "); for(int i = 0; i < languages.size(); i++) { System.out.print(languages.get(i)); System.out.print(", "); } } }
Output
ArrayList: [Java, JavaScript, Python] Iterating over ArrayList using for loop: Java, JavaScript, Python,
In the above example, we have created an arraylist named languages. Here, we have used the for
loop to access each element of the arraylist.
Example 2: Iterate through ArrayList using for-each loop
import java.util.ArrayList; class Main { public static void main(String[] args) { // Creating an array list ArrayList<String> languages = new ArrayList<>(); languages.add("Java"); languages.add("JavaScript"); languages.add("Python"); System.out.println("ArrayList: " + languages); // Using forEach loop System.out.println("Iterating over ArrayList using for-each loop:"); for(String language : languages) { System.out.print(language); System.out.print(", "); } } }
Output
ArrayList: [Java, JavaScript, Python] Iterating over ArrayList using for-each loop: Java, JavaScript, Python,
Here, we have used the for-each
loop to iterate over the ArrayList and print each element.
Example 3: Iterate over ArrayList using listIterator()
import java.util.ArrayList; import java.util.ListIterator; class Main { public static void main(String[] args) { // Creating an ArrayList ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(3); numbers.add(2); System.out.println("ArrayList: " + numbers); // Creating an instance of ListIterator ListIterator<Integer> iterate = numbers.listIterator(); System.out.println("Iterating over ArrayList:"); while(iterate.hasNext()) { System.out.print(iterate.next() + ", "); } } }
Output
ArrayList: [1, 3, 2] Iterating over ArrayList: 1, 3, 2,
In the above example, we have used the listIterator()
method to iterate over the arraylist. Here,
- hasNext() – returns true if there is next element in the arraylist
- next() – returns the next element of the arraylist