且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确使用Optional.ifPresent()

更新时间:2022-10-14 17:49:07

可选<用户> .ifPresent()需要消费者<?超级用户> 作为参数。你传递的是一个类型为void的表达式。所以这不编译。



消费者打算以lambda表达式实现:

 可选<使用者&GT; user = ... 
user.ifPresent(theUser - > doSomethingWithUser(theUser));

甚至更简单,使用方法参考:

 可选<使用者&GT; user = ... 
user.ifPresent(this :: doSomethingWithUser);

这与



可选<使用者&GT; 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().