I'm trying to learn and understand the use of lambda expressions in Java.
I have written a function within a class that returns a boolean result based on an Optional value using a lambda expression.
private boolean isNullOrEmpty(Optional<String> value) {
boolean result;
value.ifPresent(v -> result = isEmptyOrWhitespace(v));
return result;
}
isEmptyOrWhitespace is a simple function I've defined elsewhere to check if a string is null or has only whitespace:
private boolean isEmptyOrWhitespace(String value) {
return value == null || value.trim().isEmpty();
The issue is, I cannot compile this because the compiler says
variable used in lambda should be final or effectively final
For the result variable. I have seen Java: Assign a variable within lambda with a similar problem but there the problem involved String and the solution was to set it to null beforehand.
I feel I'm close. How can I fix this?
The problem is that result is not effectively final as there are more than one assignments to it.
You can use Optional.map
private boolean isNullOrEmpty(Optional<String> value) {
return value.map(v -> isEmptyOrWhitespace(v)) //Or can use a Method reference as mentioned by Bohemian@
.orElse(false);
}
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