Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Optional.ifPresentOrElse with return value [duplicate]

In Java, I have recently began to adopt the Optional type more in my code. This allows for better null-value handling and to some extend also safer code. Optional has the ifPresentOrElse method which allows you to perform a specific action for when a value is present, or a specific action for when no value is present. However, this method does not allow you to declare a return type.

Is there an easy way I can use optionals and a ifPresentOrElse-like method to return values while unwrapping an Optional?

like image 747
ImJustACowLol Avatar asked Feb 27 '26 11:02

ImJustACowLol


1 Answers

Assuming following declarations (EDIT: note Consumer and Runnable are interfaces from @ImJustACowLol's self-answer, not java.util interfaces. For case the self-answer were deleted, the interfaces are same as those in java.util except the functional interface method has generic return type instead of void. Anyway the naming should have been chosen differently.):

Consumer<InputType, OutputType> yourConsumer = ...;
Runnable<OutputType> yourRunnable = ...;
Optional<InputType> yourOptional = ...;

you can compose following statement

OutputType result = yourOptional.map(yourConsumer).orElseGet(yourRunnable);

which admittedly doesn't fit in single method call, though still is concise and readable enough, IMHO.

like image 128
Tomáš Záluský Avatar answered Mar 02 '26 00:03

Tomáš Záluský



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!