I am trying to figure out how to traverse through a 2D array. The way in which I have been doing it is by using a nested for loop. I am curious to know of any other ways in which this can be done. I just feel like I am repeatedly using nested for loops and would prefer not to.
for(int i=0; i<gameBoard.length; i++) {
for(int j=0; j<gameBoard[i].length; j++) {
}
This is the only way in which I know how to access multiple elements within the array. Are there any other ways in which to traverse through multi-dimensional arrays?
If you're looking for alternative ways to process the elements within a matrix, you could use streams.
In the following example, I'm using two IntStream
to print a matrix of int
. Note that this approach is definitely not more efficient than a traditional nested loop. this is just an alternative way.
int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
IntStream.range(0, gameboard.length)
.boxed() // boxing each int row index to an Integer
.forEach(i -> { // process each i-th row
IntStream.range(0, gameboard[i].length) // creating a nested stream to process each element of the row
.boxed() // boxing each int column index to an Integer
.forEach(j -> System.out.printf("%d ", gameboard[i][j])); // printing the i-th j-th element
System.out.println();
});
Here is an alternative version without indexes.
int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays.stream(gameboard)
.forEach(vet -> {
Arrays.stream(vet)
.forEach(x -> System.out.printf("%d ", x));
System.out.println();
});
Here is a version employing the filter
aggregate operation, since you've added in the comments that you would like to use conditional statements.
int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays.stream(gameboard)
.forEach(vet -> {
Arrays.stream(vet)
.filter(x -> x % 2 == 0) // filtering only for even numbers
.forEach(x -> System.out.printf("%d ", x));
System.out.println();
});