Optional isPresent vs orElse(null)
Clash Royale CLAN TAG#URR8PPP
up vote
10
down vote
favorite
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.
java java-8 spring-data-jpa
add a comment |Â
up vote
10
down vote
favorite
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.
java java-8 spring-data-jpa
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 at 6:50
add a comment |Â
up vote
10
down vote
favorite
up vote
10
down vote
favorite
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.
java java-8 spring-data-jpa
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.
java java-8 spring-data-jpa
edited Aug 30 at 6:58
asked Aug 27 at 21:55


Sadiq Ali
5871515
5871515
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 at 6:50
add a comment |Â
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 at 6:50
4
4
By the way, the
java.util.Date
class was supplanted years ago by java.time.Instant
.– Basil Bourque
Aug 28 at 4:19
By the way, the
java.util.Date
class was supplanted years ago by java.time.Instant
.– Basil Bourque
Aug 28 at 4:19
1
1
Neither. The whole purpose of
Optional
is to avoid null
; the first does not do this and the second is bascially just null
by another name.– Boris the Spider
Aug 28 at 6:50
Neither. The whole purpose of
Optional
is to avoid null
; the first does not do this and the second is bascially just null
by another name.– Boris the Spider
Aug 28 at 6:50
add a comment |Â
4 Answers
4
active
oldest
votes
up vote
16
down vote
accepted
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:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: 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.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 at 10:20
 |Â
show 3 more comments
up vote
4
down vote
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 at 4:10
add a comment |Â
up vote
2
down vote
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |Â
up vote
0
down vote
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 at 11:42
add a comment |Â
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
16
down vote
accepted
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:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: 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.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 at 10:20
 |Â
show 3 more comments
up vote
16
down vote
accepted
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:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: 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.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 at 10:20
 |Â
show 3 more comments
up vote
16
down vote
accepted
up vote
16
down vote
accepted
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:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: 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.
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:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: 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.
edited Aug 27 at 22:10
answered Aug 27 at 22:00
Poger
659813
659813
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 at 10:20
 |Â
show 3 more comments
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 at 10:20
2
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 at 22:05
3
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 at 22:08
1
1
If you call
get()
immediately after a check to isPresent()
then you should be fine. The method I presented just seems more clean in your case.– Poger
Aug 27 at 22:14
If you call
get()
immediately after a check to isPresent()
then you should be fine. The method I presented just seems more clean in your case.– Poger
Aug 27 at 22:14
2
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 at 22:18
2
2
The rule of thumb is: avoid
isPresent
and get
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).– Ole V.V.
Aug 28 at 10:20
The rule of thumb is: avoid
isPresent
and get
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).– Ole V.V.
Aug 28 at 10:20
 |Â
show 3 more comments
up vote
4
down vote
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 at 4:10
add a comment |Â
up vote
4
down vote
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 at 4:10
add a comment |Â
up vote
4
down vote
up vote
4
down vote
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
answered Aug 28 at 3:01


Eugene
58.9k979138
58.9k979138
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 at 4:10
add a comment |Â
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 at 4:10
3
3
Brian Goetz has acknowledged that naming the
Optional::get
method was a mistake. Should have been named Optional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png– Basil Bourque
Aug 28 at 4:10
Brian Goetz has acknowledged that naming the
Optional::get
method was a mistake. Should have been named Optional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png– Basil Bourque
Aug 28 at 4:10
add a comment |Â
up vote
2
down vote
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |Â
up vote
2
down vote
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |Â
up vote
2
down vote
up vote
2
down vote
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
edited Sep 1 at 5:42
answered Aug 28 at 4:04


Basil Bourque
94.6k23326478
94.6k23326478
add a comment |Â
add a comment |Â
up vote
0
down vote
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 at 11:42
add a comment |Â
up vote
0
down vote
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 at 11:42
add a comment |Â
up vote
0
down vote
up vote
0
down vote
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
answered Aug 28 at 3:11
Ritesh
5,60222739
5,60222739
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 at 11:42
add a comment |Â
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 at 11:42
@Boris
findById
returns Optional
and map
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.– Ritesh
Aug 28 at 11:42
@Boris
findById
returns Optional
and map
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.– Ritesh
Aug 28 at 11:42
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52047479%2foptional-ispresent-vs-orelsenull%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
4
By the way, the
java.util.Date
class was supplanted years ago byjava.time.Instant
.– Basil Bourque
Aug 28 at 4:19
1
Neither. The whole purpose of
Optional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.– Boris the Spider
Aug 28 at 6:50