I want to achieve the following:
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("someString", object.getObjectField().getValue());
If object.getObjectField()
is null, then I get a NullPointerException
. I can easily avoid it, with the following null check:
if(object.getObjectField() != null) {
linkedHashMap.put("someString", object.getObjectField().getValue());
} else {
linkedHashMap.put("someString", "N/A");
}
However, I was thinking to find a better and prettier implementation, using Java 8 Optional, but in this case I still receive a NullPointerException
:
linkedHashMap.put("someString", Optional.ofNullable(object.getObjectField().getValue()).orElse("N/A");
What would be the right approach in this case?
but in this case I still receive a NullPointerException
That's because you would still be invoking getValue()
even if getObjectField()
is null.
You can use Optional.map
to apply a function if present:
Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)
If you want to use a default value, you can just add the orElse
after that:
Optional.ofNullable(object.getObjectField()).map(ObjectType::getValue)
.ofElse("N/A")