开发中可能会需要去除一些数组中的空行空列,例如以数组格式读取Excel等等操作,这时我们就需要去除一些整的空行空列,避免一些操作出错:
public String[][] removeNullArray(String[][] content){
//获取空值的列标,及同一列标出现的次数
//获取空值的行标,及同一行标出现的次数
Map<Integer,Integer> mapCol = new TreeMap<>();
Map<Integer,Integer> mapRow = new TreeMap<>();
//用来记录删除的列数,准确确定要删除的列数,同时在进行空行的删除时,使空行的length准确
Integer flag = 0;
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
if ("".equals(content[i][j])){
if (mapCol.get(j) == null){
mapCol.put(j, 1);
}else {
mapCol.put(j, mapCol.get(j) + 1);
}
if (mapRow.get(i) == null){
mapRow.put(i, 1);
}else{
mapRow.put(i, mapRow.get(i) + 1);
}
}
}
}
//如果同一列标出现的次数等于数组的列数,那么就认为这一列为空值列
Set<Integer> integers = mapCol.keySet();
for (Integer integer : integers) {
if (mapCol.get(integer) == content.length){
for (int i = 0; i < content.length; i++) {
for (int j = integer - flag; j < content[i].length-1; j++) {
content[i][j] = content[i][j+1];
}
content[i] = Arrays.copyOf(content[i],content[i].length-1);
}
flag++;
}
}
//如果同一行标出现的次数等于该行标所在行的长度,那么就认为这一行为空值行
Set<Integer> integersRow = mapRow.keySet();
int rowIndex = 0;
for (Integer integer : integersRow) {
if (mapRow.get(integer) - flag == content[integer - rowIndex].length){
for (int i = integer - rowIndex; i < content.length - 1; i++) {
content[i] = content[i+1];
}
content = Arrays.copyOf(content, content.length - 1);
rowIndex++;
}
}
return content;
}