Iterate over Elements of Java ArrayList
To iterate over elements of ArrayList, you can use Java loop statements like Java while loop, Java For Loop or ArrayList forEach.
In this tutorial, we will go through each of these looping techniques to iterate over elements of ArrayList.
Iterate over ArrayList Elements using While Loop
In the following example, we will iterate over elements of ArrayList using Java While Loop statement. We start with index of zero, increment it by one during each iteration and iterate until the index is less than the size of this ArrayList.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Google");
names.add("Apple");
names.add("Samsung");
int index = 0;
while(index < names.size()) {
String element = names.get(index);
//work on the element
System.out.println(element);
index++;
}
}
}
Output
Google
Apple
Samsung
Iterate over ArrayList Elements using For Loop
You can iterate over elements of ArrayList using Java For Loop statement. We start with index of zero, increment it by one during each iteration and iterate until the index is less than the size of this ArrayList.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Google");
names.add("Apple");
names.add("Samsung");
for(int index = 0; index < names.size(); index++) {
String element = names.get(index);
//work on the element
System.out.println(element);
}
}
}
Output
Google
Apple
Samsung
Iterate over ArrayList Elements using Enhanced For Loop
You can also use forEach statement which executes a block of statements for each element in the ArrayList.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Google");
names.add("Apple");
names.add("Samsung");
for(String element: names) {
System.out.println(element);
}
}
}
Output
Google
Apple
Samsung
Iterate over ArrayList Elements using ArrayList.forEach()
You can also use ArrayList.forEach() statement that executes a set of statements for each element of this ArrayList, just for for-each statement in the above example.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Google");
names.add("Apple");
names.add("Samsung");
names.forEach(element -> {
System.out.println(element);
});
}
}
Output
Google
Apple
Samsung
Conclusion
In this Java Tutorial, we learned how to traverse or iterate over elements of ArrayList in Java.