我试图理解Java8中的ifPresent() API的Optional方法。
我有一个简单的逻辑:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));但这会导致编译错误:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)我当然可以做这样的事:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}但这就像一张杂乱的null支票。
如果我将代码更改为:
user.ifPresent(new Consumer<User>() {
@Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});代码变得越来越脏,这让我想到回到旧的null检查。
有什么想法吗?
发布于 2014-06-15 09:41:56
Optional<User>.ifPresent()以一个Consumer<? super User>作为参数。您传递给它的是一个类型为空的表达式。所以这不能编译。
“消费者”将作为lambda表达式实现:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));甚至更简单,使用方法引用:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);这基本上和
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
@Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});其思想是,只有当用户在场时,doSomethingWithUser()方法调用才会被执行。您的代码直接执行方法调用,并尝试将其空结果传递给ifPresent()。
发布于 2017-04-26 07:34:40
除了@JBNizet的答案之外,我对ifPresent的一般用例是将.isPresent()和.get()结合起来
旧方式:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}新途径:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})对我来说,这更直观。
发布于 2018-12-13 11:27:37
既然你可以让代码变得简单,为什么要编写复杂的代码呢?
实际上,如果您绝对要使用Optional类,那么最简单的代码就是您已经编写的.
if (user.isPresent())
{
doSomethingWithUser(user.get());
}这段代码的优点是
仅仅因为Oracle在Java8中添加了Optional类,并不意味着这个类必须在所有情况下都使用。
https://stackoverflow.com/questions/24228279
复制相似问题