I don't means return a Optional value, I mean for a method:
public void someMethod() {
Optional<Obj> obj = someService.getObj();
if (obj.isPresent()) {
....
} else {
log.info(xxxx);
return;
}
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxx
other codes
}
Is is possible to write it with Optional.ifPresent way? I mean, avoid to use the if isPresent thing.
Many thanks.
== updated:
it seems ifPresentOrElse in JDK9 can do this, but is there any way to do this in JAVA8?
I don't need this method return any value, but if the Optional not present, I want to log something.
Seems like a use case for ifPresentOrElse
as in Java-9 :
obj.ifPresentOrElse(a -> {...}, () -> {logger.info(xxxx);return; });
If you want to do nothing when the Optional
is empty, you can use ifPresent
:
public void someMethod() {
someService.getObj().ifPresent (v -> {
....
});
}
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