Optional.ifPresent() 的正确使用 [英] Proper usage of Optional.ifPresent()

查看:199
本文介绍了Optional.ifPresent() 的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to understand the ifPresent() method of the Optional API in Java 8.

我的逻辑很简单:

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

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());
            }
        });

代码越来越脏,这让我想到回到旧的null检查.

The code is getting dirtier, which makes me think of going back to the old null check.

有什么想法吗?

推荐答案

Optional.ifPresent() 需要一个 Consumer 作为参数.你传递给它一个类型为 void 的表达式.所以这不编译.

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.

消费者旨在实现为 lambda 表达式:

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);

这和

Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
    @Override
    public void accept(User theUser) {
        doSomethingWithUser(theUser);
    }
});

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

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 void result to ifPresent().

这篇关于Optional.ifPresent() 的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆