gpt4 book ai didi

java - 正确使用 Optional.ifPresent()

转载 作者:IT老高 更新时间:2023-10-28 13:51:22 26 4
gpt4 key购买 nike

我正在尝试了解 Java 8 中 Optional API 的 ifPresent() 方法。

我的逻辑很简单:

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 检查。

有什么想法吗?

最佳答案

Optional<User>.ifPresent()需要 Consumer<? super User>作为论据。您正在向它传递一个类型为 void 的表达式。所以这不编译。

Consumer 旨在实现为 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()只有当用户在场时才会执行方法调用。您的代码直接执行方法调用,并尝试将其 void 结果传递给 ifPresent() .

关于java - 正确使用 Optional.ifPresent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228279/

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