Java – how to prevent the function passed to optional orelse from being executed when optional is not empty?
•
Java
If I call a function from orelse, the function will be executed even if optional is not empty Is there any way to restrict the execution of functions only when option is empty?
Optional.ofNullable(someValue).orElse(someFunction());
Solution
Somefunction () is executed because it is a parameter passed to the method, which is evaluated before the method is executed To avoid execution, you should pass somefunction () in the supplier instance
Use orelseget instead of orelse:
Optional.ofNullable(someValue).orElseGet(SomeClass::someFunction);
or
Optional.ofNullable(someValue).orElseGet(()->someFunction());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码