如何在Java中使用可选项(Optional)时在条件块中进行空值检查?

huangapple go评论72阅读模式
英文:

how can I put null check in conditional block when using optional in java?

问题

这是代码:

Optional<Buyer> buyerOptional = Optional.ofNullable(buyerRepository.findById(buyerId).orElse(null));
Buyer buyer = buyerOptional.get();
if (buyer != null) {
    
} else if (buyerOptional == null) {
    response = utility.createResponse(500, KeyWord.ERROR, "无效的买家");
}

我想进入else if块中,如果能够提供任何建议,将会很有帮助。

英文:

this is the code

Optional&lt;Buyer&gt; buyerOptional = Optional.ofNullable(buyerRepository.findById(buyerId).orElse(null));
Buyer buyer = buyerOptional.get();
if (buyer != null) {
    
} else if (buyerOptional == null) {
    response = utility.createResponse(500, KeyWord.ERROR, &quot;Invalid buyer&quot;);
}

I want to get inside else if block, would be great if I could get any suggestion on this.

答案1

得分: 2

首先,您无需再创建Optional,因为findById已经返回了Optional。您可以使用isPresent()来检查值是否存在。

Optional<Buyer> buyerOptional = buyerRepository.findById(buyerId);
if (buyerOptional.isPresent()) {
   Buyer buyer = buyerOptional.get();
   ... // 准备响应数据
} else {
    response = utility.createResponse(500, KeyWord.ERROR, "无效的买家");
}
英文:

First of all, you don't need to create Optional again as findById already return Optional. And you can use isPresent() to check if value present or not.

Optional&lt;Buyer&gt; buyerOptional = buyerRepository.findById(buyerId);
if (buyerOptional.isPresent()) {
   Buyer buyer = buyerOptional.get();
   ... // preparing response
} else {
    response = utility.createResponse(500, KeyWord.ERROR, &quot;Invalid buyer&quot;);
}

huangapple
  • 本文由 发表于 2020年10月6日 15:25:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64221117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定