简体   繁体   中英

How to iterate only through the first row of a 2d array?

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} ?

In JAVA 2D array means 1D array of 1D arrays ; ie 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}

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.
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM