在 Java 8 中使用“可选”删除嵌入式空检查

2022-09-03 12:41:29

我替换了以下代码:

if (status.getPlace() == null) {
    row.set("CountryCode", "Unknown");
    row.set("Country", "Unknown");
} else {
    if (status.getPlace().getCountryCode() == null) {
        row.set("CountryCode", "Unknown");
    } else {
        row.set("CountryCode", status.getPlace().getCountryCode());
    }
    if (status.getPlace().getCountry() == null) {
        row.set("Country", "Unknown");
    } else {
        row.set("Country", status.getPlace().getCountry());
    }
}

有了这个:

String countryCode = Optional.ofNullable(status.getPlace())
        .filter(p -> p.getCountryCode() != null)
        .map(Place::getCountryCode)
        .orElse("Unknown");
row.set("CountryCode", countryCode);

String country = Optional.ofNullable(status.getPlace())
        .filter(p -> p.getCountry() != null)
        .map(Place::getCountry)
        .orElse("Unknown");
row.set("Country", country);

它按预期工作,但不知何故,我认为我可以做得更好。我仍然在那里进行“空”检查。

.filter(p -> p.getCountryCode() != null)

有没有办法避免上述空检查?


答案 1

您不需要空检查 - 。删除它,您的代码应该可以正常工作。.filter(p -> p.getCountry() != null)

Optional.map()返回实例本身。因此,无需应用空检查。Optional


答案 2

您根本不需要该操作。如果调用 或 返回,则返回一个空的可选值,这意味着将调用该方法来检索替代值。filterPlace::getCountryCodePlace::getCountrynullorElse


推荐