I'm looking into Java Optional and testing some usecases beyond the standard ones.
ok, let's take this example:
public void increment(Integer value) {
if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
currentValue+=value;
}
}
currentValue and endValue are Integer
.
Can the example above be converted in Java8 using Optional?
I was thinking something like that:
public void increment(Integer value) {
currentValue.filter(a-> a < (endValue.get()-value)).map(???);
}
where currentValue and endValue are Optional<Integer>
I'm actually stuck with the .map
Function.
I would appreciate any suggestion, thanks
How about this?
currentValue = currentValue.filter(it -> endValue.isPresent())
.filter(it -> it < endValue.get() - value)
.map(it -> Optional.of(it + value))
.orElse(currentValue);
OR move the value
into left side is more simpler than above.
currentValue = currentValue.map(it -> it + value)
.filter(it -> endValue.isPresent())
.filter(result -> result < endValue.get() )
.map(Optional::of)
.orElse(currentValue);
OR
currentValue = currentValue.filter(it -> it < endValue.map(end -> end - value)
.orElse(Integer.MIN_VALUE))
.map(it -> Optional.of(it + value))
.orElse(currentValue);
OR move the value
into left side is more simpler than above.
currentValue=currentValue.map(it -> it + value)
.filter(result->result<endValue.orElse(Integer.MIN_VALUE))
.map(Optional::of)
.orElse(currentValue);
OR using Optional#flatMap instead:
currentValue = currentValue.flatMap(it ->
endValue.filter(end -> it < end - value)
.map(end -> Optional.of(it + value))
.orElse(currentValue)
);
OR move the value
into the left side then can using ternary-operator simplified:
currentValue = currentValue.map(it -> it + value).flatMap(result ->
endValue.filter(end -> result < end)
.isPresent() ? Optional.of(result) : currentValue
);
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