如何转换Optional& lt; Object& gt;到可选& lt; String& gt;
我在Java 11中有这段代码
I have this code in Java 11
Object a = getObjectOrNullIfNotAvailable();
String value = a==null ? null : a.toString();
我想使用Optional编写此代码,我能想到的最好的方法是.我没有尝试运行它,但我怀疑它可以工作
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);
除了在可选组件上运行map之外,我还有任何其他想法可以实现此目的.我希望能得到下面的代码,但这是行不通的
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);
从方法的返回值中创建一个Optional似乎有些尴尬.而是让您的 getObjectOrNullIfNotAvailable()
方法首先返回Optional.然后使用 map
运算符将其转换为字符串.这是它的外观.
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);
由于某种原因,如果您不能将方法的返回值更改为 Optional
,则只需使用三元运算符保留命令式解决方案即可.没关系.
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();