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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With