Lang
Lang

Reputation: 983

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.

Upvotes: 8

Views: 10281

Answers (4)

Debashish Hota
Debashish Hota

Reputation: 59

Use Optional.ofNullable(input).orElseGet(this::methodName);

If the input is null then it goes to orElseGet logic. If input is not null then return the input value.

Please refer to section 'Difference Between orElse and orElseGet()' of https://www.baeldung.com/java-optional

Upvotes: -1

Bentaye
Bentaye

Reputation: 9756

Just throwing an idea out there, what about having a method on the service to check if the object is present? I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.

On SomeService:

public boolean isObjectPresent() {
    return getObj().isPresent();
}

Then

public void someMethod() {
    if (someService.isObjectPresent()) {
         ....
    } else {
       log.info(xxxx);
       return;
    }
}

This way you don't have to deal with the Optional in your call as you don't really care about its value

NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.

Upvotes: 0

Naman
Naman

Reputation: 31878

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

obj.ifPresentOrElse(a -> {...}, () -> {logger.info(xxxx);return; });

Upvotes: 6

Eran
Eran

Reputation: 393791

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

public void someMethod() {
    someService.getObj().ifPresent (v -> {
         ....
    });   
}

Upvotes: 3

Related Questions