0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
cvlst
  • 5
  • 2
  • 2
    You *could* use the ternary operator: `linkedHashMap.put("someString", object.getObjectField() == null ? "N/A" : object.getObjectField().getValue());` – Lino Feb 07 '22 at 13:02
  • 1
    [Related](https://stackoverflow.com/questions/56235254/optional-vs-if-else-if-performance-java-8/56235329#56235329) if not the dupe. [Another candidate](https://stackoverflow.com/questions/23454952/uses-for-optional/23464794#23464794). (didn't close because its my answer on the first one.) – Lino Feb 07 '22 at 13:04

1 Answers1

1

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")
Andy Turner
  • 137,514
  • 11
  • 162
  • 243