To iterate over a list in Java, you can use various methods such as a for loop, an enhanced for loop, or an iterator.
In this example,
numbers
and initialize it with some integer values.0
to the length of the list minus one.get
method of the list to access each element by its index.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
for (int i = 0; i < numbers.size(); i++) {
System.out.println("Element at index " + i + ": " + numbers.get(i));
}
}
}
Element at index 0: 1 Element at index 1: 2 Element at index 2: 3 Element at index 3: 4 Element at index 4: 5
In this example,
colors
and initialize it with some string values.color
represents each element in the list during each iteration.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Yellow");
colors.add("Orange");
for (String color : colors) {
System.out.println("Color: " + color);
}
}
}
Color: Red Color: Green Color: Blue Color: Yellow Color: Orange
In this tutorial, we learned How to Iterate Over a List in Java language with well detailed examples.