Home > front end >  Traversing through a 2D array
Traversing through a 2D array

Time:04-17

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. So if anyone has any other ways in which to traverse through multi-dimensional arrays that would be greatly appreciated

CodePudding user response:

If you're simply looking for alternative ways to process elements within a matrix, just for the sake of knowledge, you could use streams.

Here, I'm using two IntStreams to print a matrix of int. Note that this is definitely not more efficient than the classic nested for approach, it's just an alternative way.

int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
IntStream.range(0, gameboard.length)
        .boxed()
        .peek(i -> IntStream.range(0, gameboard[i].length)
                .boxed()
                .forEach(j -> System.out.printf("%d ", gameboard[i][j])))
        .forEach(i -> System.out.println());

Similarly, the previous code can be recreated also in a form with no indexes.

int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays.stream(gameboard)
        .peek(vet -> Arrays.stream(vet)
                .forEach(x -> System.out.printf("%d ", x)))
        .forEach(vet -> System.out.println());

EDIT

Since in the comments I've read that you would like to use a more compact form that also allows you to use conditional statements, then what you're looking for might reinforce the stream approach as you could benefit from the filter aggregate operation.

Here, I'm using the previous example to print only even numbers.

int[][] gameboard = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays.stream(gameboard)
        .peek(vet -> Arrays.stream(vet)
                .filter(x -> x % 2 == 0)
                .forEach(x -> System.out.printf("%d ", x)))
        .forEach(vet -> System.out.println());
  • Related