Jhonatan R. Santos
Jhonatan R. Santos

Reputation: 15

Is it possible to iterate through a two-dimensional array without two loops for?

For example, if I have:

int Myarray[][] = new int[][] {{1,2}, {3,4}};
for (int line=0; line < Myarray.length; line++) {
    for (int column = 0; column < Myarray[0].length; column++) {
        // do something ...
    }
}

How could I go through the entire array without the two loops?

Upvotes: 1

Views: 10822

Answers (3)

Andy Turner
Andy Turner

Reputation: 140328

You can iterate without any loops:

void recursive(int[][] array, int r, int c) {
  if (r >= array.length) return;
  if (c >= array[r].length) {
    recursive(array, r+1, 0);
  } else {
    System.out.println(array[r][c]);
    recursive(array, r, c+1);
  }
}

Then invoke with recursive(array, 0, 0) to get started.

But there is no practical benefit in doing so. This would perform poorly, because of all the extra effort involved in calling a method vs just incrementing an int. (Plus, depending upon the size of the array, you could end up with a stack overflow).

Upvotes: 2

Bohemian
Bohemian

Reputation: 425033

If you don’t need to know the line or column in the “do something” code (not stated in question), you could:

Arrays.stream(Myarray).flatMap(Arrays:stream)
    .forEach(n -> /* do something with “n”, the cell value */);

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

Well you could use just a single loop:

for (int i = 0; i < Myarray.length*Myarray.length; i++) {
    int row = i / Myarray.length;
    int col = i % Myarray.length;
    System.out.println(Myarray[row][col]);
}

But this assumes that your 2D array is square, i.e. its width and length are the same everywhere. Another way of saying this is that the 2D array is not jagged.

Demo

Note: As @Thilo mentioned above, this won't make things run faster. If you need to touch every element in your array, then my suggested code and your current double loop basically have the same complexity.

Upvotes: 8

Related Questions