我替换了下面的代码:
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)
有没有办法避免上面的空检查?
最佳答案
您不需要空检查 - .filter(p -> p.getCountry() != null)
。删除它,您的代码应该可以正常工作。
Optional.map()
返回一个 Optional
实例本身。所以不需要应用空检查。
关于java - 在 Java 8 中删除带有 'Optional' 的嵌入式空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51427615/