Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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?

like image 987
membersound Avatar asked Jan 08 '23 16:01

membersound


1 Answers

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.

like image 157
Thirler Avatar answered Jan 24 '23 15:01

Thirler