[英]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?如何仅遍历 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}
?我如何只遍历
{5, 22, 30, 40, 30}
或{96, 20, 30, 25, 25}
?
In JAVA 2D array means 1D array of 1D arrays
;在 JAVA 中,二维数组表示
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. int[][] arr = new int[2][3]
表示您创建了 2D arrays,每行2
行3
列。 Rows and columns are zero-indices , so to get access to the first row, you should use 0
index.行和列是零索引,因此要访问第一行,您应该使用
0
索引。
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]? {5, 22, 30, 40, 30}
[0] 还是{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].要检索
{5, 22, 30, 40, 30}
的 22,您可以使用 [0] [1]、[menaing First array] 和 [second element of array selected]。
Edit编辑
You need 2 for
cicles to iterate all the elements:您需要 2
for
cicles 来迭代所有元素:
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
System.Out.Println(array[row][col]);
}
}
Edit #2 To iterate only for the first array, burn the first square bracket to [0]:编辑 #2要仅对第一个数组进行迭代,请将第一个方括号刻录为 [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:您可以为此目的使用
Stream
:
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另请参阅:在 java 8 中使用 Streams 而不是 for 循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.