简体   繁体   中英

How can I return a boolean value with Optional's ifPresentOrElse?

I haven't been in contact with Optional for a while, but I have a question.

How do I convert the if else statement below using Optional? Since ifPresentOrElse doesn't return anything, it seems that it can't return true or false.

Is there any way? Or is it correct to use if else statement as before?

// Using if else statement
if (obj != null) {
    // someting to do
    return true;
} else {
    // someting to do
    return false;
}

// Using Optional
Optional.ofNullable(obj)
    .ifPresentOrElse(
            val -> {
                // if obj is not null
                // someting to do
                // return true
            }
            , () -> {
                // if obj is null
                // someting to do
                // return false
            }
    );

If you are being given an Optional , just do

return optional.isPresent();

Otherwise there's no reason to use Optional :

return obj != null;

If you want side-effects also, you could do something like this:

public static void main(String[] args) {
    Optional<String> present = Optional.ofNullable("Data");
    Optional<String> absent  = Optional.empty();
    
    System.out.printf("Value was %s\n", doSomething(present)? "present" : "absent");
    System.out.printf("Value was %s\n", doSomething(absent)? "present" : "absent");
}
    
public static boolean doSomething(Optional<String> opt)
{
    opt.ifPresentOrElse(
            v -> { System.out.printf("value is '%s'\n",v); }, 
            ()-> { System.out.println("value is absent");  }
    );
    return opt.isPresent();
}

I think you are trying to execute some code after nullity check. You could simply do, `

 Optional.ofNullable(obj)
         .map(o -> o.doOnNotNull(o))
         .orElseGet(() -> doOnNull())

Edit: If you just want to do nullity check and return boolean then you can simply use Optional.ifPresent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM