Я заменил следующий код:
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)
Есть ли способ избежать вышеуказанной нулевой проверки?