I am tasked with fixing a problem where this code returns string values but because the iterations add null elements it needs to trim or remove those. During debug the value of the array contains mostly "All elements are null", but other solutions like data.removeAll(Collections.singleton(null)); do not work because it is the elements that are null and it still returns as the original size. Is there a way to remove these elements after the iterations of the initial loop or should this be done inside the loop where data is assigned the "value"?
Code:
private String[][] getStringsFromSpreadSheet(Sheet ws) {
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[(rowNum - 1)][colNum];
int k = 0;
for (int i = 1; i < rowNum; i++) {
ws.getRow(i);
if (ws.getRow(i) != null) {
for (int j = 0; j < colNum; j++) {
if (ws.getRow(i).getCell(j) != null) {
String value = ws.getRow(i).getCell(j).toString();
if (!value.toString().isEmpty()) {
data[k][j] = value;
}
}
}
}
k++;
}
return data;
}
Collection.addAll(dataList, data)isn't doing what you think it is. What you're doing here is creating a list of arrays of string. When you try to remove null from the list, nothing comes out, because it's full of array references, none of which are null, even though the arrays themselves have null values.Listand back, including trimming nulls from it while it's in itsListform. Let me know if that helps.