[英]How to flatten a 2-dimensional array into a 1-dimensional array
How would i transfer a 2d array into a 1d array in java. 我将如何将2d数组转换为Java中的1d数组。 I have the code for the 2d array but dont know where to start.
我有二维数组的代码,但不知道从哪里开始。 The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80.
2d数组的输出为8 x 10的网格,数字范围为1-80。
public class move
{
public static void main (String[] args)
{
int[][] twoarray = new int[8][10];
int i ;
int j ;
for(i =0; i < 8; i++)
{
for(j = 0; j < 10; j++)
twoarray[i][j] = (i * 10 + j+1);
}
for(i = 0; i < 8; i++)
{
for(j = 0; j < 10; j++)
{
System.out.print(twoarray[i][j]);
System.out.print(" ");
}
System.out.println();
}
int[] array = new int[80];
}
}
Using Java 8 使用Java 8
int[] array = Stream.of(twoarray)
.flatMapToInt(IntStream::of)
.toArray();
Using Java 7 or older 使用Java 7或更旧版本
int[] array = new int[80];
int index = 0;
for (int[] row : twoarray) {
for (int val : row)
array[index++] = val;
}
You can do in your for loop: 您可以在for循环中执行以下操作:
int[] array = new int[80];
int k=0;
for(i = 0; i < 8; i++){
for(j = 0; j < 10; j++){
array[k++]=twoarray[i][j];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.