可选isPresent vs orElse(null) [英] Optional isPresent vs orElse(null)

查看:1057
本文介绍了可选isPresent vs orElse(null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中更新了Spring 8的依赖项,并被编译错误轰炸,其中 findOne()的方法定义已被 findById()现在返回可选(如果我错了,请更正我)。

I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne() has been replaced by findById() which now returns an Optional (correct me if I am wrong).

在重构时,我遇到了多种我可以选择采用的方法,因此我想要一些关于哪一种方法的首选。

While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.

第一种方法:

ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null);
if(ep != null){
    ep.setDateModified(new Date());
    expectedPackageRepository.saveAndFlush(ep);
}

第二种方法:

Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1);
if(ep.isPresent()){
    ep.get().setDateModified(new Date());
    expectedPackageRepository.saveAndFlush(ep.get());
}

还是有第三种更好的方法我错过了吗?我经历了几个问题和一些文章,但我没有找到明确的答案。

Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.

推荐答案

您还可以:

expectedPackageRepository.findById(1).ifPresent(
    ep -> {
        ep.setDateModified(new Date());
        expectedPackageRepository.saveAndFlush(ep);
    }
);

理想情况下,您还可以在括号之间提取部分( {} )到一个单独的方法。然后,你可以像这样写:

Ideally, you would also extract the part between brackets ({}) to a separate method. Then, you could write like this:

    expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);

其中:

void doSomethingWithEp(ExpectedPackage ep) {
    ep.setDateModified(new Date());
    expectedPackageRepository.saveAndFlush(ep);
}

您可以阅读 ifPresent 此处: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-

如其所述,如果值存在,它将执行指定的操作,否则不执行任何操作。

As it states, it will perform the specified action if the value is present and do nothing otherwise.

这篇关于可选isPresent vs orElse(null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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