Reputation: 943
I am a newbie to Java 8 APIs. I have this piece of code, which needs to be optimized using Java Optional.
if (Objects.nonNull(someDao.getById(id))) {
someDao.delete(id);
} else {
throw new RuntimeException();
}
I tried using Optional.ofNullable to optimize this piece of code.
Optional.ofNullable(someDao.getById(id))
.ifPresent(deleteObject)
.orElseThrow(() -> new RuntimeException("some error message"));
private Consumer<SomeObject> deleteObject = someObj-> {
someDao.delete(someObj.getId());
};
I am getting an error saying "can't invoke orElseThrow on primitive type void"
How can this be optimized to handle both data persistence and exception handling without using if-else blocks using Optional?
Upvotes: 0
Views: 1318
Reputation: 2344
I think the if-statement you have is clear and don't see why you'd want to turn it in an Optional chain.
That being said, I also didn't manage to get it all done in one chain:
SomeObject someObj = Optional.ofNullable(someDao.getById(id))
.orElseThrow(() -> new RuntimeException("some error message"));
someDao.delete(someObj.getId());
.orElseThrow
returns the value contained in the Optional if it is not null. So you can store it in a SomeObject
and then delete it.
Upvotes: 0
Reputation: 273540
You need to do this in two separate calls:
Optional<SomeType> opt = Optional.ofNullable(someDao.getById(id));
opt.ifPresent(deleteObject);
opt.orElseThrow(() -> new RuntimeException("some error message"));
Upvotes: 1