Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Optional<Object> to Optional<String> [closed]

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);
like image 698
abhaybhatia Avatar asked Jun 07 '26 08:06

abhaybhatia


1 Answers

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();
like image 120
Ravindra Ranwala Avatar answered Jun 10 '26 17:06

Ravindra Ranwala