简体   繁体   English

在java中使用可选时如何在条件块中放置空检查?

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

this is the code这是代码

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, "Invalid buyer");
}

I want to get inside else if block, would be great if I could get any suggestion on this.我想进入 else if block,如果我能得到任何建议,那就太好了。

First of all, you don't need to create Optional again as findById already return Optional .首先,您不需要再次创建Optional ,因为findById已经返回Optional And you can use isPresent() to check if value present or not.您可以使用isPresent()来检查值是否存在。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM