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?