In Java, there are several ways to print a 2D array. In this guide, we will see various programs to print 2D array using different approaches:
Note: In the previous tutorial, I have covered how to print an array(1D array).
Printing 2D Arrays
1. Using Arrays.deepToString()
You can use Arrays.deepToString()
method to print a 2D array. You can simply pass the reference of 2D array as an argument to this method in order to display all the elements.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(array));
}
}
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2. Using Nested Loop
Another simple way of displaying a 2D array is by using nested loops. In this program, we are using nested for-each loops.
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int[] row : array) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
3. Using Iterator
Another way to print an array is by converting it into a list and then using an iterator to display the elements of the list. In this example, we are using nested iterators.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (Integer[] row : array) {
List<Integer> list = Arrays.asList(row);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
4. Using Stream
You can use the Stream
API to print each element of the array. You can refer Java Stream Tutorial to learn more about Stream.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Arrays.stream(array).forEach(row -> {
Arrays.stream(row).forEach(element -> System.out.print(element + " "));
System.out.println();
});
}
}
Output:
1 2 3
4 5 6
7 8 9
5. Using Arrays.asList
For 2D arrays, you can convert each row to a list using asList() method and print it. This method belongs to java.util.Arrays
class. I have covered some of the commonly used methods here: Java Arrays Methods.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (Integer[] row : array) {
List<Integer> list = Arrays.asList(row);
System.out.println(list);
}
}
}
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Leave a Reply