Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace if(Optional.isPresent()) with an expression in functional style [duplicate]

I have the following block of code:

Optional<Integer> result = //some method that returns an Optional<Integer>;

    if(result.isPresent()) {
        return result.get();
    } else {
        return 0;
    }

and my IntelliJ suggests that I replace it with a functional expression. I see that there is a method ifPresentOrElse() inside Optional but I can't possibly figure out how to use it in this particular case.

Any suggestions? Thanks!

like image 377
Teo J. Avatar asked Dec 11 '22 05:12

Teo J.


1 Answers

Looks like orElse() is what you'd want here. https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElse-T-

Optional<Integer> result = //some method that returns an Optional<Integer>;
return result.orElse(0);
like image 96
Ben P. Avatar answered Jan 18 '23 22:01

Ben P.