leonheess
leonheess

Reputation: 21491

Simplify assign with check for null

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

Answers (2)

Yassin Hajaj
Yassin Hajaj

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

Dan Gravell
Dan Gravell

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

Related Questions