有四种方法可以删除 java 数组中的一列数据:使用 system.arraycopy() 复制数组的每一行,跳过要删除的列。使用 guava 库遍历每一行并过滤掉要删除的列。使用 apache commons lang 库直接移除列。手动遍历数组并重新构造一个新数组,排除要删除的列。

如何删除 Java 数组中一列数据
要删除 Java 数组中一列数据,有几种方法:
1. 使用 System.arraycopy()
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = new int[arr.length - 1][];
// 复制数组的每一行,跳过要删除的列
for (int i = 0; i < arr.length; i++) {
newArr[i] = new int[arr[i].length - 1];
System.arraycopy(arr[i], 0, newArr[i], 0, arr[i].length - 1);
}
登录后复制
2. 使用 Guava 库
立即学习“”;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Builder<ImmutableList<ImmutableList<Integer>>> builder = ImmutableList.builder();
// 遍历每一行并过滤掉要删除的列
for (ImmutableList<Integer> row : ImmutableList.copyOf(arr)) {
builder.add(ImmutableList.copyOf(row.subList(0, row.size() - 1)));
}
ImmutableList<ImmutableList<Integer>> newArr = builder.build();
登录后复制
3. 使用 Apache Commons Lang 库
import org.apache.commons.lang3.ArrayUtils;
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = ArrayUtils.removeColumns(arr, 1);
登录后复制
4. 手动遍历并重构数组
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = new int[arr.length][arr[0].length - 1];
// 遍历每一行并创建新数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < newArr[i].length; j++) {
if (j < arr[i].length - 1) {
newArr[i][j] = arr[i][j];
}
}
}
登录后复制
以上就是java怎么删除数组中一列数据的详细内容,更多请关注米云其它相关文章!
