gpt4 book ai didi

java - 测试 Java 可选

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:39 25 4
gpt4 key购买 nike

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

好吧,让我们举个例子:

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

currentValue 和 endValue 是 Integer .

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

我是这么想的:

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

其中 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);

ORvalue 移动到左侧比上面更简单。

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

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

ORvalue 移动到左侧比上面更简单。

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

使用Optional#flatMap相反:

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

ORvalue 移动到左侧,然后可以使用简化的三元运算符:

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

关于java - 测试 Java 可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44405222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com