user10767069
user10767069

Reputation:

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.

Upvotes: 0

Views: 49

Answers (1)

Eklavya
Eklavya

Reputation: 18430

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

Upvotes: 2

Related Questions