Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 How to return from a method if Optional is not present?

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.

like image 203
Lang Avatar asked Mar 04 '23 06:03

Lang


2 Answers

Seems like a use case for ifPresentOrElse as in Java-9 :

obj.ifPresentOrElse(a -> {...}, () -> {logger.info(xxxx);return; });
like image 116
Naman Avatar answered Apr 07 '23 14:04

Naman


If you want to do nothing when the Optional is empty, you can use ifPresent:

public void someMethod() {
    someService.getObj().ifPresent (v -> {
         ....
    });   
}
like image 34
Eran Avatar answered Apr 07 '23 14:04

Eran