Reputation: 439
I have a json like this:
{
"name": "car",
"attributes": {
"lon": 13,
"lat": 15
}
}
Sometimes some attributes can be null.
Optional<Attributes> op = Optional.ofNullable(json);
if (op.isPresent()) {
Optional<Integer> opI = Optional.ofNullable(op.get().getLon());
opI.ifPresent(....);
}
How can avoid using Optional in many lines, is there a safe way to reduce it. Imagine you have a json like this.
{"object1": {
"object2": {
"object3": {
"object4: {
and you need to access to object4 but checking if some of the previous objects are null, with my approach using optional. It wouldn't be the best and more elegant solution.
What can I do it in an elegant way using optional and reducing the code?
Upvotes: 1
Views: 401
Reputation: 45329
You just use Optional.map
, which skips the code you give it when the optional is empty
Integer lon = Optional.ofNullable(json).map(Attributes::getLon).orElse(null);
You can chain any number of intermediate map()
calls on successive optionals. map()
will skip the call to the function you give it if the optional is empty.
So, for your other case:
var object4 = Optional.ofNullable(mainObject)
.map(MainObject::getObject1)
.map(Object1:getObject2)
.map(Object2:getObject3)
.map(Object3:getObject4)
.orElse(null); //set object4 to null if anything was missing
Important to keep in mind (from the linked JavaDocs):
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.
So if any getObjectN
returns null, the resulting optional will be empty.
Upvotes: 1