[英]Optional<Integer> return a string from Optional.ifPresentOrElse() when empty?
I'm trying to get a value from an Optional to create a string, but use a constant string ("not supplied") if the value is empty.我试图从 Optional 中获取一个值来创建一个字符串,但如果该值为空,则使用常量字符串(“未提供”)。 Is there a way to use ifPresentOrElse() to return a string constant?有没有办法使用 ifPresentOrElse() 返回字符串常量? Or maybe a different call altogether?或者完全不同的电话?
final Optional<Integer> optAppId = Optional.ofNullable(appApiBean.getAppId());
...
// works, but long, clumsy,
String appIdStr = optAppId.isPresent() ? optAppId.get().toString() : NA_OPTION;
// Second part fails, because it's not void
String appIdStr = optAppId.ifPresentOrElse(s -> s.toString(), () -> NA_OPTION);
I like the idea of using the Optional capabilities directly, reducing the occurrences of the variable name, more readable code, etc., and I'd hate to introduce flag values for the Integer like '-1' so I can use ifPresent()我喜欢直接使用 Optional 功能的想法,减少变量名的出现次数,更易读的代码等,我不想为 Integer 引入标志值,如“-1”,这样我就可以使用 ifPresent()
Ideas?想法?
ifPresentOrElse
performs an action depending on whether the optional is empty or not, rather than evaluating to a value. ifPresentOrElse
根据可选项是否为空执行操作,而不是评估值。
You can use orElse
to specify the default value you want when the optional is empty.您可以使用orElse
来指定当可选为空时您想要的默认值。 orElse
will return the optional's wrapped value if it is not value, so you should first map
the optional to the value you want: orElse
将返回可选的包装值,如果它不是值,所以你应该首先map
可选到你想要的值:
String appIdStr = optAppId.map(Integer::toString).orElse(NA_OPTION);
You can also use orElseGet
, which takes a Supplier
, if you want lazy-evaluation of the default value:如果你想对默认值进行惰性评估,你也可以使用orElseGet
,它接受一个Supplier
:
String appIdStr = optAppId.map(Integer::toString).orElseGet(() -> someExpensiveOperation());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.