我尝试通过编写辅助方法来使代码更加紧凑,因为代码非常重复。
代码组成:
- 调用命令(远程 ssh,或本地命令,这部分对我的问题来说并不有趣)
- 检查是否成功
- 如果没有,请在此停止并将返回码返回给调用方法(即
return cr;
) - 如果成功,则继续执行另一个命令
我尝试创建一个辅助方法来完成这一切。如果命令执行失败,会返回 Optional<Integer>
返回码。如果它按预期工作,它将返回 Optional.empty()
.
我的问题是如何做这样的事情:
public void topMethod()
{
int cr = execCmds();
... do stuff with cr ...
}
private int execCmds()
{
executeCmd("my command").ifPresent(cr -> return cr);
executeCmd("my next command").ifPresent(cr -> return cr);
....
return 0;
}
如您所见,如果返回码有意义,我想停止流程。如果没有,就必须继续。有没有办法做到这一点? (简洁一些。)
有关信息,return cr
在 ifPresent
中无效lambda 方法。
最佳答案
使用Optional.or()
Optional.or()
是随 JDK 9 引入的,预计为 Supplier
可选
。
简而言之,方法 or()
检查应用它的 Optional
是否为空,如果是空的,则将其替换为另一个可选值。否则,如果值存在,它将返回相同的可选值(即,作为参数传递的 Supplier
不会被执行,函数会被延迟计算)。
public void topMethod() {
int cr = execCmds();
// do something with cr
}
private int execCmds() {
return executeCmd("my command")
.or(() -> executeCmd("my next command"))
.or(...) // more alternatives
.orElse(0);
}
public Optional<Integer> executeCmd(String command) {
return // something;
}
供应商流
另一种选择是创建Optional
的Supplier
流。
如果您使用 JDK 8(因此不能使用 或
),或者 executeCmd()
返回 OptionalInt
缺少方法 or()
。
Stream 会懒惰地一次处理每个 Supplier
,并且与之前的解决方案一样,每个 executeCmd()
调用仅在需要时才会发生(如果上一个命令未能提供结果)。
具体实现方式如下:
public void topMethod() {
int cr = execCmds();
// do something with cr
}
private int execCmds() {
return Stream.<Supplier<OptionalInt>>of(
() -> executeCmd("my command"),
() -> executeCmd("my next command")
// ...
) // Stream<Supplier<OptionalInt>>>
.map(Supplier::get) // Stream<<OptionalInt>>
.filter(OptionalInt::isPresent) // Stream<<OptionalInt>>
.mapToInt(OptionalInt::getAsInt) // IntStream
.findFirst() // OptionalInt
.orElse(0);
}
public OptionalInt executeCmd(String command) {
return // something;
}
关于java - 有没有办法从 ifPresent 方法向调用方法返回可选值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74390879/