hc0re
hc0re

Reputation: 1986

How to fetch object data from an ifPresentOrElse statement?

I am trying to fetch some data from and object. I have a small piece of code where:

UserAccessValidator is just a validator, the method validateAccessToAccount takes an Long, and throws and exception when the access is not granted. Simple as that.

userAccessValidator.validateAccessToAccount(
    peripheralRepository.findById(peripheralId)
        .ifPresentOrElse(p -> p.getAccount().getId(),
            () -> {throw new NotFoundException(Peripheral.class);}));

It doesn't compile, i get an information that Long is required but provided is void.

How can I fix this piece of code for it to work? I would like to get the account Id, but I do not know how to achieve this... A more detailed explaination would be very appreciated ;)

Upvotes: 1

Views: 108

Answers (1)

Eran
Eran

Reputation: 393836

ifPresentOrElse​() has a void return type, so it's not suitable to return a value.

Use map to map the value inside the Optional into the desired account ID. This would return another Optional.

Then you can call orElseThrow, which would throw the exception if the Optional is empty, and return the value stored within that Optional if not.

userAccessValidator.validateAccessToAccount(
        peripheralRepository.findById(peripheralId)
                            .map(p -> p.getAccount().getId())
                            .orElseThrow​ (() -> {throw new NotFoundException(Peripheral.class);});

Upvotes: 1

Related Questions