在 java 中使用可选时,如何在条件块中进行空检查?

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

我想进入 else if 块,如果我能对此提出任何建议,那就太好了。

首先,您不需要再次创建 Optional,因为 findById 已经 return Optional。您可以使用 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");
}