英文:
Optional<Integer> return a string from Optional.ifPresentOrElse() when empty?
问题
尝试从一个Optional
final Optional<Integer> optAppId = Optional.ofNullable(appApiBean.getAppId());
...
// 有效,但冗长和笨拙
String appIdStr = optAppId.isPresent() ? optAppId.get().toString() : NA_OPTION;
// 第二部分失败,因为它不是void
String appIdStr = optAppId.ifPresentOrElse(s -> s.toString(), () -> NA_OPTION);
我喜欢直接使用Optional的功能,减少变量名称的出现次数,使代码更可读等,我不想引入像'-1'这样的标志值,以便我可以使用ifPresent()。
有什么想法吗?
英文:
I'm trying to get a value from an Optional<Integer> to create a string, but use a constant string ("not supplied") if the value is empty. Is there a way to use ifPresentOrElse() to return a string constant? 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()
Ideas?
答案1
得分: 4
ifPresentOrElse
根据 Optional 是否为空来执行操作,而不是求得一个值。
你可以使用 orElse
来指定 Optional 为空时的默认值。如果 Optional 不为空,orElse
将返回 Optional 包裹的值,因此你应该首先使用 map
将 Optional 映射到你想要的值:
String appIdStr = optAppId.map(Integer::toString).orElse(NA_OPTION);
你还可以使用 orElseGet
,它接受一个 Supplier
,如果你希望默认值进行延迟求值,可以这样使用:
String appIdStr = optAppId.map(Integer::toString).orElseGet(() -> someExpensiveOperation());
英文:
ifPresentOrElse
performs an action depending on whether the optional is empty or not, rather than evaluating to a value.
You can use orElse
to specify the default value you want when the optional is empty. 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:
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:
String appIdStr = optAppId.map(Integer::toString).orElseGet(() -> someExpensiveOperation());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论