简体   繁体   中英

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. 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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM