I have the 2D array and printed them out backward. What I am trying to achieve is to copy each line of printed row to a regular array. Is it possible to do that?
Integer[][] testList;
testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
for (int i = 0; i < testList.length; i ) {
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] " ");
}
System.out.println();
}
CodePudding user response:
This will copy any size 2D array of ints
.
int[][] testData = { { 1, 2, 3 },{}, null, { 4, 5, 6, 7 },null,{ 8, 9 },
{ 10, 11, 12 } };
int[] result = copy2DArrays(testData);
System.out.println(Arrays.toString(result));
prints
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
- First, compute size of result array. This also handles null rows.
- if a null row is encountered, replace with an empty array for copy phase.
- Allocate the return array of computed
size
- Then for each row
- iterate thru the row, copying the value to result array indexed by
k
- iterate thru the row, copying the value to result array indexed by
- When done, return the resultant array.
public static int[] copy2DArrays(int[][] array) {
int size = 0;
for (int i = 0; i < array.length; i ) {
if (array[i] == null) {
// replace null row with empty one
array[i] = new int[]{};
continue;
}
size = array[i].length;
}
int k = 0;
int[] result = new int[size];
for (int[] row : array) {
for (int v : row) {
result[k ] = v;
}
}
return result;
}
Another, simpler option is using streams.
- stream the "2D" array
- only pass nonNull rows
- flatten each row into a single stream
- then gather them into an array.
int[] array = Arrays.stream(testData)
.filter(Objects::nonNull)
.flatMapToInt(Arrays::stream)
.toArray();
CodePudding user response:
You can create a new array and then copy the values into it:
for (int i = 0; i < testList.length; i ) {
int[] copy = new int[testList[i].length];
int copyIndex = 0;
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] " ");
copy[copyIndex ] = testList[i][j];
}
}
CodePudding user response:
The Arrays class gives you a lot of nifty features:
public static void main(String[] args) {
Integer[][] testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
int max = 0;
for (Integer[] row : testList) {
max = Math.max(max, row.length);
}
Integer[][] copy = new Integer[testList.length][max];
for (int i = 0; i < testList.length; i ) {
copy[i] = Arrays.copyOf(testList[i], copy[i].length);
}
for (int i = 0; i < testList.length; i ) {
System.out.println("Source " i ": " Arrays.toString(testList[i]));
System.out.println("Copy " i ": " Arrays.toString(copy[i]));
}
}