0

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?

1
  • 1
    Using optional here will be (slightly) less efficient and doesn't improve readability. So I would stick to the original if/else which clearly shows the intention of the code. Commented May 1, 2017 at 7:49

2 Answers 2

1

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"));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.