Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Java Optional

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

like image 950
ken Avatar asked Mar 08 '23 22:03

ken


1 Answers

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
);
like image 118
holi-java Avatar answered Mar 20 '23 11:03

holi-java