正确使用Optional.ifPresent() [英] Proper usage of Optional.ifPresent()
问题描述
我试图了解Java 8中 Optional
API的 ifPresent()
方法。
我的逻辑很简单:
可选<用户> user = ...
user.ifPresent(doSomethingWithUser(user.get()));
但是这会导致编译错误:
ifPresent(java.util.functionError:(186,74)java:'void'type not here here)
当然我可以这样做:
if(用户。 isPresent())
{
doSomethingWithUser(user.get());
}
但这就像一个杂乱的 null
check。
如果我将代码更改为:
user.ifPresent(new Consumer< User>(){
@Override public void accept(User user){
doSomethingWithUser(user.get());
}
});
代码变得越来越脏,这让我想起回到旧的 null
check。
任何想法?
可选<用户> .ifPresent()
需要消费者<?超级用户>
作为参数。你传递的是一个类型为void的表达式。所以这不编译。
消费者打算以lambda表达式实现:
可选<使用者> user = ...
user.ifPresent(theUser - > doSomethingWithUser(theUser));
甚至更简单,使用方法参考:
可选<使用者> user = ...
user.ifPresent(this :: doSomethingWithUser);
这与
<$基本相同p $ p>
可选<使用者> user = ...
user.ifPresent(new Consumer< User>(){
@Override
public void accept(User theUser){
doSomethingWithUser(theUser);
}
});
想法是 doSomethingWithUser()
只有在用户在场时才会执行方法调用。您的代码直接执行方法调用,并尝试将其voir结果传递给 ifPresent()
。
I am trying to understand the ifPresent()
method of the Optional
API in Java 8.
I have simple logic:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));
But this results in a compilation error:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)
Of course I can do something like this:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}
But this is exactly like a cluttered null
check.
If I change the code into this:
user.ifPresent(new Consumer<User>() {
@Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});
The code is getting dirtier, which makes me think of going back to the old null
check.
Any ideas?
Optional<User>.ifPresent()
takes a Consumer<? super User>
as argument. You're passing it an expression whose type is void. So that doesn't compile.
A Consumer is intended to be implemented as a lambda expression:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));
Or even simpler, using a method reference:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);
This is basically the same thing as
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
@Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});
The idea is that the doSomethingWithUser()
method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its voir result to ifPresent()
.
这篇关于正确使用Optional.ifPresent()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!