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
- 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();