Creating an Optional out of the return value of a method seems a bit awkward. Rather let your getObjectOrNullIfNotAvailable()
method return an Optional in the first place. Then use the map
operator to convert it in to a string. Here's how it looks.
Optional<Object> oa = someOptionalReturningMethod();
String value = oa.map(Object::toString).orElse(null);
For some reason if you can't change the return value of the method to an Optional
, just leave the imperative solution using the ternary operator. Nothing wrong with that.
String value = a==null ? null : a.toString();