[英]Merge 3 arrays into a multidimensional array
I have three separate arrays that I would like to merge into a multidimensional array我有三个单独的数组,我想将它们合并到一个多维数组中
Array 3 [1, 1, 2, 4, 1, 2, 1, 1]
Array 2 [1, 1, 2, 2, 1, 2, 6, 1]
Array 1 [1, 3, 1, 1, 1, 1, 2, 1]
The output that I would like to have is where all the arrays are in one multidimensional array where they are all stacked on top of each other.我想要的输出是所有数组都在一个多维数组中,它们都堆叠在彼此的顶部。
Finial Array =最终数组 =
Array 3
Array 2
Array 1
How would I go about doing this?我该怎么做呢?
If I understood your question correctly, you're looking for something like this:如果我正确理解了您的问题,那么您正在寻找这样的东西:
import java.util.stream.IntStream;
public class MultiDimensionalArrayDemo {
public static void main(String[] args) {
final int ROWS = 3;
final int COLUMNS = 10;
int array1 [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int array2 [] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int array3 [] = { 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
int finalArray[][] = new int[ROWS][];
finalArray[0] = array1;
finalArray[1] = array2;
finalArray[2] = array3;
System.out.println("Initial bi-dimensional array:");
for(int i=0; i<ROWS; i++) {
for(int j=0; j<COLUMNS; j++) {
System.out.printf("%2d ",finalArray[i][j]);
}
System.out.println();
}
for(int i=0; i<ROWS-1; i++) {
for(int j=0; j<COLUMNS; j++) {
if(finalArray[i][j]==0) {
moveColumnUp(IntStream.range(i, ROWS).mapToObj(obj -> finalArray[obj]).toArray(int[][]::new),ROWS-i,j);
}
}
}
System.out.println("After transformation:");
for(int i=0; i<ROWS; i++) {
for(int j=0; j<COLUMNS; j++) {
System.out.printf("%2d ",finalArray[i][j]);
}
System.out.println();
}
}
private static void moveColumnUp(int matrix [][], int numberOfRows, int columnIndex) {
int firstRowElement = matrix[0][columnIndex]; // temporarily store first row so it can be placed last
for(int i=0; i<numberOfRows-1; i++) {
matrix[i][columnIndex] = matrix[i+1][columnIndex];
}
matrix[numberOfRows-1][columnIndex] = firstRowElement;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.