如何转换Optional& lt; Object& gt;到可选& lt; String& gt; [英] How to convert Optional<Object> to Optional<String>

查看:81
本文介绍了如何转换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();

这篇关于如何转换Optional&amp; lt; Object&amp; gt;到可选&amp; lt; String&amp; gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆