英文:
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<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.
答案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<Buyer> buyerOptional = buyerRepository.findById(buyerId);
if (buyerOptional.isPresent()) {
Buyer buyer = buyerOptional.get();
... // preparing response
} else {
response = utility.createResponse(500, KeyWord.ERROR, "Invalid buyer");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论