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函数.
我要感谢任何建议,谢谢
这个怎么样?
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)
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |