gpt4 book ai didi

java - 在 Java 8 中删除带有 'Optional' 的嵌入式空检查

转载 作者:太空狗 更新时间:2023-10-29 22:51:55 26 4
gpt4 key购买 nike

我替换了下面的代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com