在 Java 8 中使用“可选”删除嵌入式空检查
我替换了以下代码:
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)
有没有办法避免上述空检查?