问题
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);
回答1:
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();
回答2:
Use:
String value = Optional.ofNullable(getObjectOrNullIfNotAvailable()).map(Object::toString).orElse(null);
Otherwise, you can check if an Object is null and return in that case a String with "null" inside with String.valueOf(Object obj) or Objects.toString(Object obj). Eg.
String value = Objects.toString(getObjectOrNullIfNotAvailable())
回答3:
You can use map followed by orElse no need to separate them like so :
String value = Optional.ofNullable(a)
.map(Object::toString)
.orElse(null);
来源:https://stackoverflow.com/questions/57730799/how-to-convert-optionalobject-to-optionalstring