Optional.ifPresent() 的正确用法

2022-08-31 08:11:15

我试图理解Java 8中API的方法。ifPresent()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

有什么想法吗?


答案 1

Optional<User>.ifPresent()采用 as 参数。您正在向它传递一个类型为 void 的表达式。所以这不会编译。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);
    }
});

这个想法是,只有当用户在场时,才会执行方法调用。您的代码直接执行方法调用,并尝试将其 void 结果传递给 。doSomethingWithUser()ifPresent()


答案 2

除了@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
})

对我来说,这更直观。


推荐