0

I have a beginner question.

How do I iterate through only the first row of an two dimensional array in Java?

For example, if I have:

int[][] array = {{5, 22, 30, 40, 30}, {96, 20, 30, 25, 25}};

How do I only iterate through {5, 22, 30, 40, 30} or {96, 20, 30, 25, 25}?

3 Answers3

0

In JAVA 2D array means 1D array of 1D arrays; i.e. each row is the separate 1D array (therefore they can have different sizes).

int[][] arr = new int[2][3] means that you have created 2D arrays with 2 rows and 3 columns in each row. Rows and columns are zero-indices, so to get access to the first row, you should use 0 index.

int[][] array = {{5, 22, 30, 40, 30}, {96, 20, 30, 25, 25}};

System.out.println(Arrays.toString(array[0]));    // {5, 22, 30, 40, 30}
System.out.println(Arrays.toString(array[1]));    // {96, 20, 30, 25, 25}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

Simple:

The first square brackets it's for ¿Wich array you are looking for? {5, 22, 30, 40, 30} [0] or {96, 20, 30, 25, 25} [1] ?

Then, the second square brackets are for: ¿Wich element inside the array are you looking for? To retrieve the 22 of {5, 22, 30, 40, 30} you sould use [0] [1], [menaing First array] and [second element of array choosen].

Edit

You need 2 for cicles to iterate all the elements:

for (int row = 0; row < array.length; row++) {    
    for (int col = 0; col < array[row].length; col++) {
       System.Out.Println(array[row][col]);
    }
}

Source here

Edit #2 To iterate only for the first array, burn the first square bracket to [0]:

for (int col = 0; col < array[0].length; col++) {
       System.Out.Println(array[0][col]); // Iterating only the first array elements.
    }
Kevin
  • 93
  • 6
  • Thanks very much. This saves my time. But Please check this "System.Out.Println(array[0][col])" will throw an error. it's rather System.out.println(array[0][col]) is the appropriate one for the sake of us the beginners. I stand to be corrected – Anas Jun 07 '22 at 09:03
0

You can use Stream for this purpose:

int[][] array = {{5, 22, 30, 40, 30}, {96, 20, 30, 25, 25}};

System.out.println(Arrays.stream(array[0])
        .mapToObj(String::valueOf)
        .collect(Collectors.joining(" "))); //5 22 30 40 30

System.out.println(Arrays.stream(array[1])
        .mapToObj(String::valueOf)
        .collect(Collectors.joining(" "))); //96 20 30 25 25

See also: Using Streams instead of for loop in java 8