Different ways to Iterate over an ArrayList in Java
ArrayList
ArrayList is a collection that is ordered by index. This means that when you add elements to the ArrayList the order of the list is determined by insertion order. Lists are zero based this means that you can access the first element in the collection with index zero e.g.: colors.get(0)
. Unlike Sets a List allows duplicate and null elements. A list will be initialised with a default size but they can grow dynamically.
Characteristics
- zero based
- allows duplicate elements
- allows null elements
- ordered by index
- unsorted
- grows dynamically
Iterate over an ArrayList Examples
In Java you have many possibilities to iterate over a list. I have the most commonly used listed.
package com.memorynotfound.collections.list;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author MemoryNotFound.com
*/
public class ListIterateProgram {
public static void main(String... args){
List<String> colors = Arrays.asList("red", "orange", "yellow", "green", "blue", "indigo", "violet");
// Basic loop
for (int i = 0; i < colors.size(); i++){
String color = colors.get(i);
printColor(color);
}
// Enhanced for loop
for (String color : colors) {
printColor(color);
}
// Basic loop with iterator
for (Iterator<String> it = colors.iterator(); it.hasNext(); ){
String color = it.next();
printColor(color);
}
// Iterator with while loop
Iterator<String> it = colors.iterator();
while (it.hasNext()){
String color = it.next();
printColor(color);
}
// JDK 8 streaming example lambda expression
colors.stream().forEach(color -> printColor(color));
// JDK 8 streaming example method reference
colors.stream().forEach(ListIterateProgram::printColor);
// JDK 8 for each with lambda
colors.forEach(color -> printColor(color));
// JDK 8 for each
colors.forEach(ListIterateProgram::printColor);
}
private static void printColor(String color){
System.out.println("color: " + color);
}
}
Sample output
Because ArrayList is a sequential list hence insertion and retrieval order is the same. We know that all elements have the following output:
red
orange
yellow
green
blue
indigo
violet