I have optional object:
Optional<Detail> newestDetail;
I would like to return newestDetail.getId()
or if newestDetail
is null return null
.
Do we have more sophisticated approach of doing this, than following?
return newestDetail.isPresent()?newestDetail.get().getId():null;
You can create an optional object from a nullable value using the static factoy method Optional. ofNullable . The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed. Optional<Job> optJob = Optional.
Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.
The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.
Using an Optional instead of using null to indicate failure/no result has some advantages: It clearly communicates that "failure" is an option. The user of your method does not have to guess whether null might be returned.
Map the value to an Optional
with the id field and turn that one into a null
value if it is empty:
return newestDetail.map(Detail::getId).orElse(null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With