I want to exit the current method/function in case a value of an Optional is not present.
i tried a naive approach to put a return statement into the .orElseGet() but that didn't seem to work. The best alternative so far seems to be:
private void foo(Set<ISomeObject> someIterable) {
Optional<ISomeObject> myObjectOpt = someIterable
.stream()
.filter(...)
.findFirst();
if(!myObjectOpt.isPresent()){
return;
}
ISomeObject myObject = myObjectOpt.get();
// do something with myObject
}
This doesn't seem better readable than the good old Nullcheck, any alternatives?
myObjectis a field? if so: do you want to update it only ifsomeIterablereturns a value? If not... are you using it later in the same method and only want to use it, if it is present? theifmight be ok for the first... (but theelseis not necessary then)...ifPresentmight be what you are looking for in the latter case...nulland no matching element. So using a statement likeif(!myObjectOpt.isPresent()) returnmight be fine in some situations. When it comes to readability, there is no reason to declare themyObjectlong before its initialization. Just writeISomeObject myObject = myObjectOpt.get();after the presence has been checked…