To iterate over a Two-Dimensional List in Java, you can use nested for loops, with an outer loop iterating over rows and an inner loop iterating over columns. The outer loop iterates over each row of the 2D list, while the inner loop iterates over each element in the current row.
In this example,
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<List<Integer>> matrix = new ArrayList<>();
matrix.add(List.of(1, 2, 3));
matrix.add(List.of(4, 5, 6));
matrix.add(List.of(7, 8, 9));
for (List<Integer> row : matrix) {
for (Integer element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
1 2 3 4 5 6 7 8 9
In this example,
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<List<String>> matrix = new ArrayList<>();
matrix.add(List.of("apple", "banana"));
matrix.add(List.of("cherry", "orange"));
for (List<String> row : matrix) {
for (String element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
apple banana cherry orange
In this tutorial, we learned How to Iterate over a Two Dimensional List in Java language with well detailed examples.