Reputation: 21491
How to simplify the following working code?
Explanation why it is necessary to have the null-check in case you don't know Apache POI: row.getCell(0).getStringCellValue()
would throw a NullPointerException because row.getCell(0)
will be null
if the cell is empty.
String datapoint = (row.getCell(0) != null) ? row.getCell(0).getStringCellValue() : "";
I tried this but it isn't working because the NPE will be thrown within the null-check:
String datapoint = Optional.ofNullable(row.getCell(0).getStringCellValue()).orElse("");
Upvotes: 0
Views: 147
Reputation: 21995
Use Optional#map
Optional.ofNullable(row)
.map(r -> r.getCell(0))
.map(cell -> cell.getStringCellValue())
.orElse("");
If you know for sure that row
is not null, then abstract yourself from the first layer of encapsulation
Optional.ofNullable(r.getCell(0))
.map(cell -> cell.getStringCellValue())
.orElse("");
Upvotes: 1
Reputation: 8275
Optional.ofNullable(row.getCell(0))
.map(cell -> cell.getStringCellValue())
.orElse("");
You could use a method reference instead of the lambda, but I wasn't sure which API you were using.
E.g.
Optional.ofNullable(row.getCell(0))
.map(Cell::getStringCellValue)
.orElse("");
Upvotes: 4