Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get field of optional object or return null

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;
like image 355
Rudziankoŭ Avatar asked Dec 08 '17 12:12

Rudziankoŭ


People also ask

How do I return an optional 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.

How do you check if the optional object is null or not?

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.

What does Optional get return if empty?

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.

Is null better than optional?

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.


1 Answers

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);
like image 160
Henrik Aasted Sørensen Avatar answered Sep 26 '22 23:09

Henrik Aasted Sørensen