[英]How can I return a boolean value with Optional's ifPresentOrElse?
I haven't been in contact with Optional for a while, but I have a question.我已经有一段时间没有与 Optional 联系了,但我有一个问题。
How do I convert the if else statement below using Optional?如何使用 Optional 转换下面的 if else 语句? Since ifPresentOrElse doesn't return anything, it seems that it can't return true or false.
由于 ifPresentOrElse 没有返回任何内容,因此它似乎无法返回 true 或 false。
Is there any way?有什么办法吗? Or is it correct to use if else statement as before?
或者像以前一样使用 if else 语句是否正确?
// Using if else statement
if (obj != null) {
// someting to do
return true;
} else {
// someting to do
return false;
}
// Using Optional
Optional.ofNullable(obj)
.ifPresentOrElse(
val -> {
// if obj is not null
// someting to do
// return true
}
, () -> {
// if obj is null
// someting to do
// return false
}
);
If you are being given an Optional
, just do如果你得到一个
Optional
,就做
return optional.isPresent();
Otherwise there's no reason to use Optional
:否则没有理由使用
Optional
:
return obj != null;
If you want side-effects also, you could do something like this:如果你还想要副作用,你可以这样做:
public static void main(String[] args) {
Optional<String> present = Optional.ofNullable("Data");
Optional<String> absent = Optional.empty();
System.out.printf("Value was %s\n", doSomething(present)? "present" : "absent");
System.out.printf("Value was %s\n", doSomething(absent)? "present" : "absent");
}
public static boolean doSomething(Optional<String> opt)
{
opt.ifPresentOrElse(
v -> { System.out.printf("value is '%s'\n",v); },
()-> { System.out.println("value is absent"); }
);
return opt.isPresent();
}
I think you are trying to execute some code after nullity check.我认为您正在尝试在无效检查后执行一些代码。 You could simply do, `
你可以简单地做,`
Optional.ofNullable(obj)
.map(o -> o.doOnNotNull(o))
.orElseGet(() -> doOnNull())
Edit: If you just want to do nullity check and return boolean
then you can simply use Optional.ifPresent()
编辑:如果您只想进行无效检查并返回
boolean
那么您可以简单地使用Optional.ifPresent()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.