Issue
I have this code in Java 11
Object a = getObjectOrNullIfNotAvailable();
String value = a==null ? null : a.toString();
I want to write this code using Optional, the best I could come up with is. I haven't tried running it but I suspect it will work
Optional<Object> oa = Optional.ofNullable(getObjectOrNullIfNotAvailable());
Optional<String> oas = oa.map(a -> a.toString());
String value = oas.orElse(null);
Any ideas how I can accomplish this besides running map on the optional. I was hoping for something like the code below but this doesn't work
Optional<Object> oa = Optional.ofNullable(getObjectOrNullIfNotAvailable());
String value = oa.ifPresentOrElse(a -> a.toString(), a -> null);
Solution
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();
Answered By - Ravindra Ranwala
Answer Checked By - Robin (JavaFixing Admin)