membersound
membersound

Reputation: 86727

How to extract a field parameter from optional, or throw exception if null?

String result = service.getResult();

if (result == null) {
    DaoObject obj = crudRepository.findOne(..);
    if (obj != null) {
        result = obj.getContent();
    } else {
        throw NotFoundException();
    }
}

service.process(result);

If DaoObject would be an Optional<DaoObject>, what could I do to achieve the same as above using java 8?

Something with .orElseThrow(() -> new NotFoundException());, but how would the above code look exactly with streams?

Sidequestion: should I use () -> new NotFoundException() or NotFoundException::new?

Upvotes: 5

Views: 2674

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You can do:

Optional<DaoObject> obj = crudRepository.findOne(..);
result = obj.orElseThrow(NotFoundException::new).getContent();

Sidequestion: should I use () -> new NotFoundException() or NotFoundException::new?

That's just a matter of choice. Both expressions will do the same.

Upvotes: 2

Thirler
Thirler

Reputation: 20760

Your assumption is correct. This would result in the following code:

Optional<DaoObject> obj = crudRepository.findOne(..);

result = obj.orElseThrow(() -> new NotFoundException()).getContent();

Or if you prefer you can split the statement to make it more readable:

DoaObject object = obj.orElseThrow(() -> new NotFoundException());
result = object.getContent();

Note that () -> new NotFoundException() and NotFoundException::new are exactly the same, so it is just a matter of what you think is more readable.

Upvotes: 8

Related Questions