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?