问题
I am trying to remove the null elements from the old 2d array and put it in a new 2d array, but the new 2d array is outputting all null elements.
String[][] status = new String[P][M];
String[][] newStatus = new String[P][M];
for (int i = 0; i < status.length; i++) {
for (int j = 0; j < status.length; j++) {
if (status[i][j] != null) {
newStatus[i][j] = status[i][j];
}
}
}
Original 2d array:
[[O, X, null, O, O, null, null], [null, null, O, null, null, O, O]]
I want it to look like this:
[[O, X, O, O], [O, O, O]]
It's outputting this:
[[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null]]
I am not that familiar with 2d arrays, so if someone could help it would be much appreciated. Thank you
回答1:
You can iterate over this array and for each row filter out the null elements and collect the remaining ones toArray:
String[][] arr1 = {
{"O", "X", null, "O", "O", null, null},
{null, null, "O", null, null, "O", "O"}};
String[][] arr2 = Arrays.stream(arr1)
.map(row -> Arrays.stream(row)
// filter out null elements
.filter(Objects::nonNull)
// new array
.toArray(String[]::new))
.toArray(String[][]::new);
// output
Arrays.stream(arr2).map(Arrays::toString).forEach(System.out::println);
[O, X, O, O]
[O, O, O]
See also: Move null elements for each row in 2d array to the end of that row
回答2:
I'd try this to get the values correctly replaced, assuming status
has had values assigned. The problem is that arrays are a fixed size (in this case P by M), so unless you're replacing the null values with something, you can't decrease the size of the 2D array, or have each row/column vary in length from the previous, imagine 2D arrays as a fixed grid of squares and each value is on a corner.
String[][] status = new String[P][M];
String[][] newStatus = new String[P][M];
for (int i = 0; i < status.length; i++) {
int y = 0;
for (int j = 0; j < status.length; j++) {
if (status[i][j] != null) {
newStatus[i][j - y] = status[i][j];
} else {
newStatus[i][M - y - 1] = " ";
y++;
}
}
}
this should provide
[[O,X,O,O, , , ],[O, O, O, , , , ]]
来源:https://stackoverflow.com/questions/64202403/remove-null-from-old-2d-array-and-put-the-not-null-elements-in-a-new-2d-array