测试Java可选

ken*_*ken 4 java optional java-8

我正在研究Java Optional并测试一些超出标准用途的用例.

好的,我们来看看这个例子:

public void increment(Integer value) {
        if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
            currentValue+=value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

currentValue和endValue是Integer.

上面的例子可以使用Optional在Java8中转换吗?

我在想这样的事情:

public void increment(Integer value) {     
        currentValue.filter(a-> a < (endValue.get()-value)).map(???);
    }
Run Code Online (Sandbox Code Playgroud)

其中currentValue和endValue是 Optional<Integer>

我实际上坚持使用.map函数.

我要感谢任何建议,谢谢

hol*_*ava 6

这个怎么样?

currentValue = currentValue.filter(it -> endValue.isPresent())
                           .filter(it -> it < endValue.get() - value)
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);
Run Code Online (Sandbox Code Playgroud)

或者value向左移动比上面更简单.

currentValue = currentValue.map(it -> it + value)
                           .filter(it -> endValue.isPresent())
                           .filter(result -> result < endValue.get() )
                           .map(Optional::of)
                           .orElse(currentValue);
Run Code Online (Sandbox Code Playgroud)

要么

currentValue = currentValue.filter(it -> it < endValue.map(end -> end - value)
                                                      .orElse(Integer.MIN_VALUE))
                           .map(it -> Optional.of(it + value))
                           .orElse(currentValue);
Run Code Online (Sandbox Code Playgroud)

或者value向左移动比上面更简单.

currentValue=currentValue.map(it -> it + value)
                         .filter(result->result<endValue.orElse(Integer.MIN_VALUE))
                         .map(Optional::of)
                         .orElse(currentValue);
Run Code Online (Sandbox Code Playgroud)

或者使用Optional#flatMap代替:

currentValue = currentValue.flatMap(it ->
    endValue.filter(end -> it < end - value)
            .map(end -> Optional.of(it + value))
            .orElse(currentValue)
);
Run Code Online (Sandbox Code Playgroud)

或者移动value到左侧然后可以使用三元运算符简化:

currentValue = currentValue.map(it -> it + value).flatMap(result ->
    endValue.filter(end -> result < end)
            .isPresent() ? Optional.of(result) : currentValue
);
Run Code Online (Sandbox Code Playgroud)

  • 如果`current + value> end`,这些片段会将`currentValue`设置为空而不是保持原样. (3认同)
  • 而不是`currentValue = ... .map(Optional :: of).orElse(currentValue);`,你可以写`... .ifPresent(v - > currentValue = Optional.of(v));` (2认同)