To iterate over a list in Java with index, you can use a traditional for loop or a for-each loop along with the size()
method of the List interface.
In this example,
numbers
with integer elements.size()
method of the list to get the number of elements.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(10, 20, 30, 40, 50));
for (int i = 0; i < numbers.size(); i++) {
System.out.println("Element at index " + i + " is: " + numbers.get(i));
}
}
}
Element at index 0 is: 10 Element at index 1 is: 20 Element at index 2 is: 30 Element at index 3 is: 40 Element at index 4 is: 50
In this tutorial, we learned How to Iterate Over a List with Index in Java language with well detailed examples.