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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With