Java 8 Optional isPresent vs orElse(null)

  • A+

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.

1st approach:

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

2nd approach:

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.

Thanks in advance.


You can also do:

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:



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

You can read the documentation of ifPresent here:

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: